# Exceptions and stack unwinding

> A throw creates an exception object in special storage, searches outward for the first handler whose type matches under a short list of rules, and destroys every automatic object on the way. When no handler matches, std::terminate runs, and whether anything was unwound first is up to the implementation.

- **Source:** C++ Atlas (https://cppatlas.com/topics/exceptions-and-stack-unwinding)
- **Track:** Exceptions and error handling
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [except.pre] (https://eel.is/c++draft/except.pre), [except.throw] (https://eel.is/c++draft/except.throw), [except.ctor] (https://eel.is/c++draft/except.ctor), [except.handle] (https://eel.is/c++draft/except.handle), [except.terminate] (https://eel.is/c++draft/except.terminate), [except.uncaught] (https://eel.is/c++draft/except.uncaught), [propagation] (https://eel.is/c++draft/propagation), [except.nested] (https://eel.is/c++draft/except.nested)
- **cppreference links:** [Exceptions](https://en.cppreference.com/w/cpp/language/exceptions), [throw expression](https://en.cppreference.com/w/cpp/language/throw), [Handling exceptions (catch)](https://en.cppreference.com/w/cpp/language/catch), [try block](https://en.cppreference.com/w/cpp/language/try), [std::terminate](https://en.cppreference.com/w/cpp/error/terminate), [std::exception_ptr](https://en.cppreference.com/w/cpp/error/exception_ptr), [std::nested_exception](https://en.cppreference.com/w/cpp/error/nested_exception), [std::uncaught_exceptions](https://en.cppreference.com/w/cpp/error/uncaught_exception)
- **Prerequisites:** raii-and-resource-management, inheritance-and-virtual-functions

## The one idea

A `throw` does three separate things. It creates an **exception object**, a fresh object whose type is the static type of the operand. It then searches the dynamically enclosing `try` blocks, innermost first, for a handler whose type matches that object. Finally, if a handler is found, it **unwinds** the stack to that handler, destroying every automatic object whose scope is being left, and enters the handler.

Almost every surprise comes from forgetting that these are separate. The handler you write receives the exception object, not your operand. Matching ignores the conversions you would expect in a function call. And unwinding is only promised if a handler is actually found.

> **Mental model.** Throwing copies your operand into a hidden object. Catch clauses are tried top to bottom with a much stricter notion of "fits" than overload resolution. Destructors run on the way out only once a match is known to exist.

## The exception object and where it lives

The exception object is copy-initialized from the operand. Its type is the operand's static type with top-level cv-qualifiers removed and arrays and functions decayed to pointers, so `throw "abc"` throws a `const char*`. Throwing through a `Base&` that refers to a `Derived` throws a `Base`, sliced.

The storage is allocated in an unspecified way, and the standard says only that it is never obtained from the global allocation functions. Itanium-ABI implementations such as GCC and Clang use a runtime allocator with an emergency pool, so an out-of-memory condition can still be reported. The object lives until the last active handler for it exits by any means other than rethrowing, or until the last `std::exception_ptr` referring to it is destroyed, whichever is later.

The type must be complete, must not be abstract, and since the resolution of CWG 1863 it must be copy-constructible from a `const` lvalue, because `std::current_exception` may need to copy it. GCC 16 and Clang 21 do not diagnose a move-only exception type, so this is a rule that compilers happen not to enforce, not one you can rely on being harmless.

```cpp
#include <cstdio>

struct Base { virtual const char* name() const { return "Base"; } virtual ~Base() = default; };
struct Derived : Base { const char* name() const override { return "Derived"; } };

void rethrow_sliced(Base& b) { throw b; }   // exception object has type Base

int main() {
  Derived d;
  try { rethrow_sliced(d); }
  catch (Derived&) { std::puts("Derived"); }
  catch (Base& b)  { std::puts(b.name()); }   // prints Base
}
```

## How a handler matches

Handlers of a `try` block are examined in the order they appear, and the first match wins, even if a later one would fit better. For an exception object of type `E`, a handler of type `T`, `const T`, `T&` or `const T&` matches when:

- `T` and `E` are the same type, ignoring top-level cv-qualification;
- `T` is an unambiguous public base class of `E`;
- `T` is a pointer or pointer-to-member type, the handler is `T` or `const T&` (not a plain non-const reference), and `E` converts to `T` by a standard pointer conversion, a qualification conversion or a function pointer conversion; or
- `T` is a pointer or pointer-to-member type and `E` is `std::nullptr_t`.

That is the whole list. There are no integral promotions, no arithmetic conversions and no user-defined conversions.

```cpp
#include <cstdio>

struct Base {};
struct Hidden : private Base {};

int main() {
  try { throw 42; }
  catch (long)   { std::puts("long"); }      // not taken: no int -> long here
  catch (...)    { std::puts("other"); }     // prints other

  try { throw Hidden{}; }
  catch (Base&)  { std::puts("base"); }      // not taken: Base is a private base
  catch (...)    { std::puts("other"); }     // prints other

  try { throw nullptr; }
  catch (int*)   { std::puts("int*"); }      // taken: nullptr_t matches any pointer handler
}
```

A `catch (...)` handler must be the last one in its `try` block, or the program is ill-formed. Putting a derived-class handler after a base-class handler is legal but dead code, and both GCC and Clang warn about it.

> **Pitfall.** GCC 16 and Clang 21 both let a handler of type `void*&` catch a thrown `int*`, which the standard does not allow: pointer conversions apply only to by-value and `const&` handlers, because a non-const reference to `void*` cannot refer to an `int*` object. Write pointer handlers by value if you ever need them.

### By value or by reference

A handler parameter is initialized from the exception object, which is an lvalue. Catching by value therefore copies, slices polymorphic exceptions to the handler's type, and runs a copy constructor that, if it throws, calls `std::terminate`. Catching by reference binds directly to the exception object, so virtual calls see the dynamic type and modifications are visible if the exception is rethrown. Catch class types by `const&`, or by `&` if you intend to modify them.

## Rethrowing: `throw;` versus `throw e;`

A bare `throw;` rethrows the exception object currently being handled. It does not copy, it does not slice, and it keeps the dynamic type. Writing `throw e;` creates a brand new exception object copy-initialized from `e`, using `e`'s static type.

```cpp
#include <cstdio>
#include <stdexcept>

int main() {
  try {
    try { throw std::out_of_range("index"); }
    catch (const std::exception& e) { throw; }   // same out_of_range object
  } catch (const std::out_of_range&) { std::puts("out_of_range"); }

  try {
    try { throw std::out_of_range("index"); }
    catch (const std::exception& e) { throw e; } // new std::exception, sliced
  } catch (const std::out_of_range&) { std::puts("out_of_range");
  } catch (const std::exception&)    { std::puts("exception"); }   // prints exception
}
```

A bare `throw;` evaluated when no exception is being handled calls `std::terminate`. It may appear in any function called from a handler, not only lexically inside one, which makes the "Lippincott function" idiom possible: a single function that rethrows and translates every exception type into an error code.

## Stack unwinding and function-try-blocks

Once a handler is found, control passes to it and every automatic object constructed since its `try` block was entered is destroyed in reverse order of construction. The same applies inside constructors: if a constructor throws, the fully constructed bases and members of that object are destroyed, but the object's own destructor never runs, because its lifetime never began. If the object was created by a `new` expression, the matching deallocation function is called. A delegating constructor is the exception: once the target constructor has finished, the object exists, and its destructor is called.

During unwinding, `std::uncaught_exceptions()` counts exceptions that have been thrown but whose handler has not yet been entered. A destructor that records the count at construction and compares it at destruction can tell whether it is running because of an exception, which is how scope guards decide between commit and rollback. The older `std::uncaught_exception()` returned a `bool` and could not tell nested cases apart; it was deprecated in C++17 and removed in C++20.

A **function-try-block** wraps an entire function body, including a constructor's member initializer list, in a `try`. It is the only way to see an exception thrown by a base or member initializer.

```cpp
#include <cstdio>
#include <stdexcept>

struct Member { Member() { throw std::runtime_error("member"); } };

struct Holder {
  Member m;
  Holder() try : m() {
  } catch (const std::exception& e) {
    std::printf("saw %s\n", e.what());
  }   // flowing off the end rethrows: Holder cannot be half-built
};

int main() {
  try { Holder h; } catch (const std::exception&) { std::puts("still thrown"); }
}
```

> **Standardese.** [except.handle] says that if control reaches the end of a handler of a constructor's or destructor's function-try-block, the current exception is rethrown. Referring to a non-static member or base of the object inside such a handler is undefined behavior, because those subobjects have already been destroyed.

For an ordinary function, flowing off the end of a function-try-block handler is like flowing off the end of the body: fine for `void`, undefined behavior for a function that should return a value, and an implicit `return 0;` in `main`.

## When `std::terminate` is called

The standard lists the situations in [except.terminate]. The ones you meet in practice are:

- no matching handler exists for a thrown exception;
- an exception tries to leave a function with a non-throwing exception specification, including any destructor not explicitly marked `noexcept(false)`;
- a function called directly by the unwinding machinery, such as a destructor of a local being destroyed or the copy constructor of a by-value handler parameter, exits via an exception;
- `throw;` is evaluated with no exception being handled;
- an exception escapes the initialization or destruction of a variable with static or thread storage duration, a function registered with `std::atexit`, or the initial function of a `std::thread`.

When no matching handler is found, it is **implementation-defined** whether the stack is unwound before `std::terminate` is called. GCC and Clang with the Itanium ABI search for a handler first and do not unwind at all if none exists, so destructors of locals in `main` do not run. That is why an RAII object can never be relied on to flush a log on an uncaught exception, and why a `catch (...)` in `main` matters.

```cpp
#include <cstdio>

struct Flush { ~Flush() { std::puts("flushed"); } };

int main() {
  Flush f;
  throw 1;   // std::terminate; with GCC and Clang, "flushed" is never printed
}
```

## Carrying exceptions across boundaries

`std::exception_ptr` is a shared-ownership handle to an exception object. `std::current_exception()` inside a handler returns one referring to the exception being handled, or to a copy of it, which is the reason for the copy-constructibility rule. `std::rethrow_exception(p)` throws that object again somewhere else, for example on another thread. `std::promise::set_exception` and `std::async` use exactly this mechanism, as described in the futures-promises-and-async topic.

`std::nested_exception` captures the current exception when it is constructed. `std::throw_with_nested(e)` throws an object of a type derived from both `e`'s type and `std::nested_exception`, so a high-level error can carry its low-level cause. `std::rethrow_if_nested(e)` rethrows that cause if `e` has one, and otherwise does nothing.

```cpp
#include <cstdio>
#include <exception>
#include <stdexcept>

int main() {
  try {
    try { throw std::runtime_error("disk full"); }
    catch (...) { std::throw_with_nested(std::logic_error("save failed")); }
  } catch (const std::logic_error& e) {
    std::puts(e.what());                            // save failed
    try { std::rethrow_if_nested(e); }
    catch (const std::runtime_error& cause) { std::puts(cause.what()); }   // disk full
  }
}
```

## What to remember

- A `throw` copy-initializes an exception object of the operand's static type; throwing through a base reference slices.
- Handlers are tried in order; the first match wins, and `catch (...)` must come last.
- Matching allows exact type, unambiguous public base, pointer and qualification conversions, and `nullptr_t` to pointer; nothing else.
- Catch by reference; by value copies, slices, and can terminate if the copy throws.
- `throw;` rethrows the same object; `throw e;` throws a new, possibly sliced, copy.
- Unwinding destroys automatic objects in reverse order and fully built subobjects of a failing constructor; the failing object's destructor never runs.
- A constructor's function-try-block handler always rethrows when it reaches its end.
- With no matching handler, whether the stack unwinds is implementation-defined, and GCC and Clang do not unwind.
- `exception_ptr`, `throw_with_nested` and `uncaught_exceptions` let exceptions be stored, chained and detected.

## Concept Map Outline

- **Exceptions and stack unwinding:** Throw creates an object, the search finds a handler, unwinding destroys locals on the way.
  - **Exception object:** Copy-initialized from the throw operand, with the operand's static type.
    - **Static type:** Throwing through a Base& throws a sliced Base; arrays decay, so throw "abc" throws const char*.
    - **Unspecified storage:** Allocated in an unspecified way, never by the global allocation functions.
    - **Lifetime:** Lives until the last handler exits without rethrowing and the last exception_ptr to it is gone.
    - **Type requirements:** Complete, not abstract, and copyable from a const lvalue since CWG 1863.
  - **Handler matching:** Handlers are tried in order of appearance; the first match wins.
    - **Allowed matches:** Same type, unambiguous public base, pointer or qualification conversion, nullptr_t to pointer.
    - **No other conversions:** No promotions, arithmetic or user-defined conversions: catch (long) misses an int.
    - **catch (...) last:** A catch-all that is not the last handler makes the program ill-formed.
    - **Catch by reference:** By value copies and slices; by reference sees the dynamic type and can modify the object.
  - **Rethrowing:** Two spellings with very different effects.
    - **throw;:** Rethrows the same exception object, keeping its dynamic type; terminates if none is active.
    - **throw e;:** Creates a new exception object of e's static type, slicing derived exceptions.
  - **Stack unwinding:** Automatic objects since the try block are destroyed in reverse order of construction.
    - **Failing constructor:** Built subobjects are destroyed; the object's own destructor never runs.
    - **Function-try-block:** Catches initializer exceptions; a constructor's handler always rethrows at its end.
    - **uncaught_exceptions:** Counts exceptions thrown but not yet caught; lets scope guards detect unwinding.
  - **std::terminate:** Called when exception handling itself cannot continue.
    - **No handler:** Whether the stack is unwound first is implementation-defined; GCC and Clang do not unwind.
    - **noexcept violated:** An exception leaving a non-throwing function, including a default destructor.
    - **Throw during unwinding:** A destructor run by unwinding that exits via an exception terminates the program.
  - **Transporting exceptions:** Library tools to store, move and chain exceptions.
    - **exception_ptr:** current_exception captures, rethrow_exception throws again, even on another thread.
    - **nested_exception:** throw_with_nested attaches the current exception; rethrow_if_nested recovers it.

## Standardese Quiz Questions

### Question 1 [warmup] ([except.handle])

What does this program print?

```cpp
#include <cstdio>

int main() {
  try { throw 42; }
  catch (long)   { std::puts("long"); }
  catch (double) { std::puts("double"); }
  catch (...)    { std::puts("other"); }
}
```

A. `long`
B. `double`
C. `other`
D. Ill-formed: `42` is ambiguous between the `long` and `double` handlers

**Answer (C):** `other`

**Why:** Handler matching does not use integral or floating conversions. An `int` exception object only matches a handler for `int`, a base class (not applicable here), or a pointer type through pointer conversions. Neither `long` nor `double` matches, so `catch (...)` is taken. The tempting `long` answer applies function-call conversion rules, which handlers do not use.

### Question 2 [warmup] ([except.throw])

What does this program print?

```cpp
#include <cstdio>
#include <stdexcept>

int main() {
  try {
    try { throw std::out_of_range("index"); }
    catch (const std::exception& e) { throw e; }
  }
  catch (const std::out_of_range&) { std::puts("out_of_range"); }
  catch (const std::exception&)    { std::puts("exception"); }
}
```

A. `exception`
B. `out_of_range`
C. Both lines
D. Nothing; `std::terminate` is called

**Answer (A):** `exception`

**Why:** `throw e;` creates a new exception object copy-initialized from `e`, and the type of that object is the static type of `e`, which is `std::exception`. The `out_of_range` part is sliced away, so only the second handler matches. A bare `throw;` would have rethrown the original `out_of_range` object and printed `out_of_range`.

### Question 3 [warmup] ([except.handle], [dcl.init.general])

What does this program print?

```cpp
#include <cstdio>

struct Base { virtual const char* name() const { return "Base"; } virtual ~Base() = default; };
struct Derived : Base { const char* name() const override { return "Derived"; } };

int main() {
  try { throw Derived{}; }
  catch (Base b) { std::puts(b.name()); }
}
```

A. `Derived`, because the exception object is a `Derived`
B. `Base`
C. Nothing: a `Base` handler does not match a `Derived` exception
D. Undefined behavior

**Answer (B):** `Base`

**Why:** The handler matches because `Base` is an unambiguous public base of `Derived`. But a by-value handler parameter is copy-initialized from the exception object, so `b` is a separate `Base` object, sliced, and the virtual call sees its dynamic type `Base`. Catching by `const Base&` would bind to the `Derived` exception object and print `Derived`.

### Question 4 [tricky] ([except.throw], [except.handle])

What does this program print?

```cpp
#include <cstdio>
#include <string>

int main() {
  try { throw "disk full"; }
  catch (const std::string& s) { std::puts("string"); }
  catch (const char* p)        { std::puts("pointer"); }
}
```

A. `string`, because the first handler that can accept the value wins
B. Nothing; `std::terminate` is called because no handler has array type
C. Ill-formed: an array cannot be thrown
D. `pointer`

**Answer (D):** `pointer`

**Why:** The exception object's type is the operand's type with arrays decayed to pointers, so it is `const char*`. Handlers are tried in order, but a handler only matches through the narrow rules of [except.handle], which exclude user-defined conversions such as `std::string`'s converting constructor. The first handler is skipped and the pointer handler is taken.

### Question 5 [tricky] ([except.handle], [except.ctor])

What does this program print?

```cpp
#include <cstdio>
#include <stdexcept>

struct Member { Member() { throw std::runtime_error("m"); } };

struct Holder {
  Member m;
  Holder() try : m() {
  } catch (const std::exception&) {
    std::puts("handler");
  }
};

int main() {
  try { Holder h; std::puts("built"); }
  catch (const std::exception&) { std::puts("outer"); }
}
```

A. `handler` then `outer`
B. `handler` then `built`
C. `outer` only; a function-try-block cannot catch initializer exceptions
D. `handler`, then `std::terminate` is called

**Answer (A):** `handler` then `outer`

**Why:** A constructor's function-try-block does see exceptions from member initializers, so `handler` is printed. When control reaches the end of such a handler, the exception is implicitly rethrown, because the object cannot exist with a member that was never constructed. The outer handler catches it and prints `outer`; `built` is never reached. Swallowing the exception, as the first option assumes, is impossible here.

### Question 6 [tricky] ([except.ctor], [except.terminate])

What happens when this program runs?

```cpp
#include <cstdio>

struct Bad {
  ~Bad() noexcept(false) { throw 2; }
};

int main() {
  try {
    Bad b;
    throw 1;
  } catch (int i) {
    std::printf("caught %d\n", i);
  }
}
```

A. Prints `caught 1`
B. Prints `caught 2`; the newer exception replaces the older one
C. `std::terminate` is called
D. Undefined behavior

**Answer (C):** `std::terminate` is called

**Why:** Throwing `1` finds the handler and starts unwinding, which destroys `b`. The destructor is called directly by the unwinding mechanism and exits via an exception, which is one of the listed cases where `std::terminate` is called. `noexcept(false)` only allows the destructor to throw when no unwinding is in progress; there is no rule that lets one exception replace another.

### Question 7 [standardese] ([except.terminate], [except.handle])

What does the standard say about whether `flushed` is printed?

```cpp
#include <cstdio>

struct Flush { ~Flush() { std::puts("flushed"); } };

int main() {
  Flush f;
  throw 1;
}
```

A. It is always printed: unwinding precedes `std::terminate`
B. It is never printed: `std::terminate` is called before any destructor
C. It is implementation-defined whether the stack is unwound, so it may or may not be printed
D. The program has undefined behavior

**Answer (C):** It is implementation-defined whether the stack is unwound, so it may or may not be printed

**Why:** No handler matches, so `std::terminate` is called, and [except.terminate] makes it implementation-defined whether the stack is unwound first. GCC and Clang search for a handler before unwinding and do not run `~Flush`, which makes "never printed" tempting, but that is a property of those implementations, not a guarantee. The behavior is defined: the program terminates.

### Question 8 [standardese] ([except.throw], [basic.stc.dynamic.allocation])

Which statement about the storage of an exception object does the C++23 standard guarantee?

A. It is obtained from `operator new`, so replacing `operator new` intercepts it
B. It lives in the stack frame of the function that executed the `throw`
C. It has static storage duration, so only one exception can exist at a time
D. It is allocated in an unspecified way, but never by the global allocation functions

**Answer (D):** It is allocated in an unspecified way, but never by the global allocation functions

**Why:** [except.throw] says the memory is allocated in an unspecified way, and [basic.stc.dynamic.allocation] adds that the global allocation functions are not used for it. Implementations typically use a runtime function with an emergency pool so `std::bad_alloc` can still be thrown. The stack-frame answer cannot be right, because the thrower's frame is destroyed during unwinding while the object must survive into the handler, and several exceptions can be alive at once.
