Intermediate⏱️ 8 min📘 Topic 30 of 32

⚠️ Exception Handling in C++ — try, catch, throw Explained

Master C++ exception handling — try, catch, throw, standard exception classes, and when to throw vs return error codes. Beginner-friendly examples + interview Q&A.

Exceptions let a function signal that something went wrong — and let the caller handle it cleanly, separately from normal logic.

🧪 The 3 keywords

  • throw — raise an exception
  • try — wrap code that might throw
  • catch — handle the exception
#include <stdexcept>

int divide(int a, int b) {
  if (b == 0) throw std::runtime_error("division by zero");
  return a / b;
}

int main() {
  try {
    std::cout << divide(10, 0);
  } catch (const std::exception& e) {
    std::cerr << "caught: " << e.what();
  }
}

📚 Standard exception classes

  • std::runtime_error — generic runtime issue
  • std::invalid_argument — bad function input
  • std::out_of_range — index out of bounds
  • std::logic_error — programming bug
  • std::bad_alloc — memory allocation failed

⚡ noexcept

Mark functions that cannot throw. Helps the compiler optimize and signals intent.

💻 Code Examples

Catching multiple types

try {
  // ... some risky code
} catch (const std::invalid_argument& e) {
  std::cerr << "bad input: " << e.what();
} catch (const std::exception& e) {
  std::cerr << "other: " << e.what();
} catch (...) {
  std::cerr << "unknown error";
}
Output:
Order matters — most specific first.

Custom exception

class FileError : public std::runtime_error {
public:
  FileError(const std::string& msg) : std::runtime_error(msg) {}
};

throw FileError("data.txt missing");
Output:
Custom types let callers handle specific cases.

⚠️ Common Mistakes

  • Catching by value: `catch (std::exception e)` — slices the exception, loses derived type info. Always catch by reference.
  • Using exceptions for normal control flow — they're slow on the throw path.
  • Throwing strings or ints — loses type/category info.
  • Destructors that throw — leads to terminate() during stack unwinding.
  • Catching `...` (catch-all) and swallowing — at least log it.

🎯 Interview Questions

Real questions asked at top product and service-based companies.

Q1.What is an exception?Beginner
An object representing an error or abnormal condition. Thrown via `throw`, caught by a matching `catch` block.
Q2.Why catch exceptions by reference?Intermediate
By value would COPY the exception, potentially slicing (losing derived type information). By reference preserves the actual type and avoids copying.
Q3.When should you throw an exception vs return an error code?Intermediate
Throw for truly exceptional, rare conditions. Return an error or std::optional for expected, recoverable failures.
Q4.What is std::exception?Intermediate
The base class for all standard exceptions. Provides a virtual `what()` method returning a C-string description.
Q5.What does `noexcept` do?Advanced
Declares that a function does NOT throw exceptions. If it does at runtime, the program calls std::terminate. Enables compiler optimizations.

🧠 Quick Summary

  • throw → try → catch.
  • Throw subclasses of std::exception; catch by const reference.
  • Order catches from most specific to most general.
  • Use exceptions for exceptional cases, error codes for expected failures.
  • Destructors must not throw; mark non-throwing functions noexcept.