Intermediate level · Module 4: Files, Streams and Exceptions in C++ · Lesson 3 of 3
Exceptions and Exception Safety
Throw and catch exceptions deliberately, use the standard exception types and write code that stays correct when exceptions occur.
In this lesson you will
- Throw and catch standard exception types by reference
- Write exception-safe code using RAII
Key concepts
throw and catch by const referencestd::runtime_errorexception safetynoexcept
The lesson
Throw an exception when a function cannot do its job: throw std::runtime_error("cannot open " + path);. Catch by const reference — catch (const std::exception& e) — and use e.what() for the message. Catching by value slices derived exception types.
Catch exceptions where you can act on them, usually near the user interface, and let them pass through lower layers. Do not use exceptions for normal control flow such as ending a loop.
Code is exception-safe when resources are not leaked and objects stay valid if an exception is thrown. RAII members make this automatic. Mark functions that never throw, such as simple getters and move operations, noexcept.
Step by step
- Throw a runtime_error from a loading function when a file is missing.
- Catch it in main by const reference and print what().
- Show that a raw new before a throw leaks, then fix it with a container.
- Mark a simple getter noexcept.
Practice activity
Add consistent exception handling to the pharmacy program: low-level functions throw, the menu catches and reports.
Expected result: Every error reaches the user as a clear message, and AddressSanitizer reports no leaks.
Check your understanding
-
Why catch exceptions by const reference?
Show answer
To avoid copying and slicing derived exception types.
-
What makes code exception-safe?
Show answer
Resources are released and objects remain valid even when an exception is thrown, typically through RAII.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.