LOGBOOK

HELP

Quiz Entry - updated: 2026.07.06

How do you handle exceptions in C++?

throw raises an exception, try wraps the risky code, and catch handles it.

throw unwinds the stack until a matching catch handles it, running destructors on the way

* A throw unwinds the stack — running local destructors (RAII cleanup) as it goes — until a catch whose type matches handles it. *

try {
    if (denominator == 0) {
        throw runtime_error("Division by zero!");
    }
    result = numerator / denominator;
}
catch (const runtime_error& e) {
    cout << "Error: " << e.what() << endl;
}
catch (...) {
    cout << "Unknown error" << endl;
}

Key points:

  • throw raises an exception object and unwinds the stack until a matching handler is found
  • catch handles a specific exception type; catch it by const reference to avoid slicing/copies
  • catch (...) is the catch-all, for any exception type
  • e.what() returns a human-readable message

Common standard exception types: std::runtime_error, std::invalid_argument, std::out_of_range (all derive from std::exception).

Tip: As the stack unwinds, local objects' destructors run — so RAII objects release their resources automatically even on the error path.

Go deeper:

From Quiz: REVE1 / C++ Programming | Updated: Jul 06, 2026