Module lessons (2/4)
Exceptions, Stack Unwinding & RAII Exception Safety
throw, try/catch for const&, std::exception hierarchy, noexcept and guaranteed release of resources in stack unwinding.
What you'll learn in this lesson
- Report exceptional errors with
throwand capture them for constant reference (catch (const std::exception& e)). - Observe Stack Unwinding live: the mechanism by which C++ destroys all RAII objects before entering
catch. - Understand the meaning and importance of
noexceptand the three guarantees of exception safety.
Overview
When an error prevents a function from maintaining its preconditions (for example, failed to open a critical file or out-of-bounds index at .at()), C++ allows you to throw an exception with throw. The program moves up the call stack until it finds a compatible catch block.
Always cast objects of the <stdexcept> hierarchy (like std::runtime_error, std::invalid_argument, std::out_of_range) by value, and capture them by constant reference (const std::exception&) to avoid object slicing and preserve the virtual method e.what():
Sections covered in this lesson
- 11.
throw,try / catchandconst std::exception& - 22. Interactive Simulator: RAII Lifecycle & Stack Unwinding
- 33. The Three Guarantees of Exception Safety +
noexcept - 44. Why Destroyers Should Never Throw Exceptions
- 5Practical exercises
- 6Check for understanding
Unlock "Exceptions, Stack Unwinding & RAII Exception Safety" and the full Course C++ curriculum
throw, try/catch for const&, std::exception hierarchy, noexcept and guaranteed release of resources in stack unwinding.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course C++ plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.