Exception Handling: try, catch, throw in C++
Exceptions separate error detection from error handling: throw launches an error object up the call stack until a matching catch block handles it, skipping every intermediate return-code check. Code that can fail wraps in try, handlers declare the types they accept, and uncaught exceptions terminate via std::terminate.
Catch by const reference (catch (const std::runtime_error& e)) to avoid slicing derived information, order handlers from most-derived to base, and let destructors run during unwinding β stack unwinding destroys every local on the way out, which is exactly why RAII cleanup is exception-safe by construction.
throw launches
throw std::runtime_error("nope"); creates an error object and unwinds the stack looking for a handler.
try marks the region
Code that might throw sits in try { ... } β only exceptions from inside are eligible for the attached handlers.
catch matches by type
Handlers try in order; catch (const std::exception& e) catches the whole standard family β put derived types first.
Unwinding destroys locals
Every local between throw and catch is properly destructed β RAII guards make cleanup automatic even on error paths.
#include <iostream>#include <stdexcept>Β int divide(int a, int b) { if (b == 0) throw std::runtime_error("divide by zero"); return a / b;}Β int main() { try { std::cout << divide(7, 0) << std::endl; } catch (const std::runtime_error& e) { std::cout << "caught: " << e.what() << std::endl; } return 0;}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself β building beats watching.