Skip to content

Chapter 21 of 31

Exception Handling

Use try, catch, throw, guarantees, RAII, and custom exception types safely.

36 minutes 10 quick checksBy Subha Prasad
Lesson 21 of 31Course navigation

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.

Which keyword signals an exception?
What does stack unwinding do?
How should standard exceptions usually be caught?
What does noexcept communicate?
What is the strong exception guarantee?
What does catch (...) handle?
How is the current exception rethrown?
Why throw exception objects by value?
What is the basic exception guarantee?
Why are destructors normally noexcept?

0 of 10 checks passed

Your progress is saved on this device.