Module 7 · Templates, Exceptions, Namespaces and Files — topic 2 of 4
Exception Handling
Signal and handle errors with throw, try and catch. Learn standard exception types, catching by reference, rethrowing, custom exceptions, noexcept and exception safety.
Learning objectives
- Throw and catch exceptions by reference
- Use the standard exception hierarchy and write custom exceptions
- Understand stack unwinding and exception safety
Definition
Exception handling transfers control from athrowexpression to the nearest matchingcatchhandler up the call stack, destroying local objects along the way (stack unwinding).
Introduction
Error codes must be checked after every call, and constructors can't return them. Exceptions separate the normal path from error handling: the code that detects a problem throws, and a caller that can deal with it catches.
Why it matters
The standard library reports errors with exceptions (at, stoi, new), so every C++ programmer must handle them.
Combined with RAII, exceptions make error handling both concise and leak-free.
Detailed explanation
throw std::invalid_argument("message"); creates an exception object. try { ... } catch (const std::invalid_argument& e) { e.what(); } handles it.
Catch by const reference to avoid slicing and copies. Handlers are tried in order, so put derived types before base types; catch (...) catches anything.
Stack unwinding: as the exception propagates, destructors of all fully constructed local objects run — which is why RAII resources are released automatically.
Hierarchy: std::exception → std::logic_error (invalid_argument, out_of_range, domain_error) and std::runtime_error (overflow_error, range_error), plus std::bad_alloc.
noexcept declares that a function won't throw; if it does, std::terminate is called. Destructors and move operations should be noexcept.
Exception-safety levels: basic (no leaks, valid state), strong (operation either fully succeeds or has no effect), no-throw.
Syntax
- Include
<stdexcept>for the standard exception classes. throw;inside a handler rethrows the current exception.- Don't use exceptions for ordinary control flow.
Code examples
Catching a library exception
index 5 is out of range program continues
Throwing your own
age 25 error: age out of range
More examples
Custom exceptions and stack unwinding
begin withdraw end withdraw begin withdraw end withdraw insufficient funds, short by 150 balance 300
Step-by-step explanation
InsufficientFundsderives fromstd::runtime_errorand carries extra data.- The first withdrawal succeeds; the second throws.
- Before the handler runs,
Audit's destructor prints "end withdraw" — stack unwinding. - The specific handler is listed before the general
std::exceptionone.
Expected output
Running “Custom exceptions and stack unwinding” prints exactly:
Practical applications
- Web frameworks convert exceptions into HTTP 500 responses.
- Parsers throw on malformed input.
- Database libraries throw on connection failures.
Best practices
- Throw by value, catch by const reference.
- Derive custom exceptions from std::exception classes.
- Use RAII so cleanup happens during unwinding.
Common mistakes
Catching by value
Avoid
Prefer
By value slices derived exceptions and copies them.
Base handler before derived
Avoid
Prefer
Handlers are tried in order; the base handler catches everything first.
Important notes
- An exception that escapes
main(or a noexcept function) callsstd::terminate. - Some environments (games, embedded) disable exceptions and use error codes or
std::optional/std::expected(C++23) instead.
Key takeaways
- throw signals, try/catch handles, by const reference.
- Unwinding runs destructors of local objects.
- Order handlers from most to least specific.
Try it yourself
- 1Write
int to_int(const std::string&)that wrapsstd::stoiand rethrows a customParseErrorwith the bad text. - 2Show that a
std::vectormember is freed when a constructor throws.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
9 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerHow should exceptions be caught?
- BeginnerWhat happens to local objects when an exception propagates out of a function?