C++C++ Explainer
C++ · 7 · Advanced / Job-Ready31 / 36 · 86%

Exception Safety Guarantees

Four levels of promise your function can make when something throws.

Examples: basic, strong, nothrow, noexcept

shortcuts: ← prev · → next · M mark
1

The Four Levels

State which one every public function provides.

Complexity
No guaranteeavoidmay corrupt or leak
Basicvalid stateinvariants hold, values unspecified
Strongcommit or rollbackas if never called
Nothrownoexceptnever throws
2

Achieving Strong Safety

Do all the throwing work first, then commit with non-throwing operations.

Example
example
void Container::add(const Item& item) {
    auto copy = data_;        // may throw — nothing committed yet
    copy.push_back(item);     // may throw — still nothing committed
    data_.swap(copy);         // noexcept: the commit point
}
3

noexcept

A promise, enforced by std::terminate if you break it.

Example
example
void cleanup() noexcept;                     // must not throw
Buffer(Buffer&&) noexcept;                   // enables vector move
static_assert(std::is_nothrow_move_constructible_v<Buffer>);
4

Rules That Prevent Disaster

Two hard rules and one habit.

Common pitfalls
  • ✕Never let an exception escape a destructor — during unwinding it calls std::terminate.
  • ✕Catch by const reference (catch (const std::exception& e)), never by value.
  • ✕Use RAII everywhere so unwinding cleans up automatically.
  • ✕Don't use exceptions for ordinary control flow — return std::optional or std::expected.