Modern C++ • C++20 baseline
Exceptions and Exception-Safe Design
Use exceptions for exceptional failures while keeping invariants intact during unwinding.
An exception propagates until a matching handler is found; stack objects are destroyed as the stack unwinds. This is why RAII is essential to exception safety. Catch exceptions by const reference when handling them, and avoid catching an exception only to hide or discard the failure.
Key points
- Use exceptions for failures that callers cannot reasonably ignore.
- Prefer error values for expected alternatives that are part of ordinary control flow.
Example
#include <stdexcept>
#include <string>
int parse_level(const std::string& text) {
const int value = std::stoi(text);
if (value < 1 || value > 5) {
throw std::out_of_range("level must be from 1 to 5");
}
return value;
}
What to expect
parse_level("3") returns 3; invalid text or a value outside the range throws an exception.
Practice exercise
Add a boundary test for 1, 5, 0, and 6. Decide which callers should catch the exception.
Key idea: Exception safety depends on objects remaining valid and resources being released during unwinding.