Lesson content
Read, practise, then check your understanding
Exceptions separate error reporting from the normal return path. throw creates an exception; stack unwinding destroys automatic objects until a matching handler is found. Throw descriptive objects by value and catch polymorphic exceptions by const reference.
#include <stdexcept>
#include <string>
double divide(double numerator, double denominator) {
if (denominator == 0.0) {
throw std::invalid_argument{"denominator is zero"};
}
return numerator / denominator;
}
try {
auto result = divide(10, 0);
} catch (const std::exception& error) {
// log error.what()
}
Catch specific exceptions before base types. throw; rethrows the current exception without slicing. A catch-all catch (...) can clean up or translate an error but should not silently discard it.
Safety guarantees
The no-throw guarantee promises success; the strong guarantee promises failure leaves state unchanged; the basic guarantee preserves invariants and prevents leaks. RAII makes all three practical because destructors release resources during unwinding. Destructors should not emit exceptions, especially while another exception is active.
Use exceptions for failures a caller cannot ignore locally, not routine branching. noexcept documents that a function will not escape with an exception; violating it calls std::terminate. Error codes, std::optional, or std::expected may better represent expected absence or domain failures. Keep exception boundaries clear across threads, C APIs, and process/plugin boundaries.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.