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.
* 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:
throwraises an exception object and unwinds the stack until a matching handler is foundcatchhandles a specific exception type; catch it byconstreference to avoid slicing/copiescatch (...)is the catch-all, for any exception typee.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:
Exceptions — cppreference — throw/try/catch semantics and stack unwinding.
Exception handling — Wikipedia — the concept and its history.
Exceptions and error handling — isocpp FAQ — when and how to use them well.