Modern C++20 Features · 8 min read · Intermediate
Exceptions & Exception Safety
Throw standard exceptions cleanly, catch by const reference, and rely on RAII for automatic cleanup during stack unwinding.
What you'll learn
- Throw standard exception types from <stdexcept> like std::invalid_argument
- Catch exceptions by const reference (const std::exception& e)
- Understand how RAII destructors run automatically during stack unwinding
In C++, the idiom is “throw by value, catch by const reference” (catch (const std::exception& e)). Catching by reference avoids object slicing and unnecessary copies. Because of RAII, every local std::vector, std::string, and std::unique_ptr is destroyed cleanly when an exception unwinds the stack.
Fill-in-the-Blank Exercise
Throw & Catch by Const Reference
Throw std::invalid_argument and catch std::exception by const reference.
try {
std::invalid_argument("Negative price");
} catch ( std::exception& e) {
std::cout << e.what() << "\n";
}Live Code Lab
C++exceptions.cpp
Expected OutputClick “Run Live” to compile with GCC 13 (C++20)
5 Caught: Division by zero
Check Your Understanding
Score: 0 / 1
1. What is the recommended way to catch C++ exceptions?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.