Learn C++
#include "exceptionhandling/exceptions.hpp"

Exception Handling: try, catch, throw in C++

//concept

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.

//how it works
1

throw launches

throw std::runtime_error("nope"); creates an error object and unwinds the stack looking for a handler.

2

try marks the region

Code that might throw sits in try { ... } β€” only exceptions from inside are eligible for the attached handlers.

3

catch matches by type

Handlers try in order; catch (const std::exception& e) catches the whole standard family β€” put derived types first.

4

Unwinding destroys locals

Every local between throw and catch is properly destructed β€” RAII guards make cleanup automatic even on error paths.

//example
#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;
}
Output
caught: divide by zero
1divide(7, 0) detects the zero denominator and throws β€” no error code, no sentinel return.
2The exception unwinds straight out of divide into the try's handler, skipping the cout line.
3The catch matches by type and e.what() carries the message into the printed line.
//use cases
Reporting constructor failures, which have no return value to carry errors
Propagating I/O and parse errors past layers that can't handle them
Catching by const reference to preserve derived exception details
Marking non-throwing operations noexcept for move and swap guarantees

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself β€” building beats watching.