A C++ destructor declared noexcept(false) throws while the stack is unwinding from another exception; what happens, and how should it report its failure instead?
answer
- two exceptions at once
- destruction during unwinding
- count in flight at construction
- uncaught_exceptions, plural
basics
~20 sstd::terminate is called: an exception escaping a destructor that runs during stack unwinding is a terminate case even when the destructor is noexcept(false). Report the failure without throwing in that situation, detected by comparing std::uncaught_exceptions() with its value at construction.
solid answer
~40 sDuring unwinding the runtime destroys the automatic objects between the `throw` and the handler. If one of those destructors exits via an exception, the standard calls `std::terminate`; `noexcept(false)` only lets the exception escape during *normal* scope exit. A destructor that wants to throw on normal exit but not during unwinding records `std::uncaught_exceptions()` in its constructor and compares in the destructor: a larger count means it is being destroyed because of an exception, so it logs instead of throwing. Use the plural function, from C++17: the singular `std::uncaught_exception()` gave the wrong answer for objects destroyed inside a handler's own cleanup and was removed in C++20. The cleaner design is an explicit `flush()` or `commit()` that throws, with a non-throwing destructor.
code
cpp · 19 lines#include <exception>
#include <iostream>
#include <stdexcept>
struct AuditLog {
~AuditLog() noexcept(false) { // opted out of implicit noexcept
std::cerr << "in flight: " << std::uncaught_exceptions() << '\n';
throw std::runtime_error("audit flush failed");
}
};
int main() {
try {
AuditLog log;
throw std::runtime_error("insert failed"); // log is destroyed during unwinding
} catch (const std::exception& e) {
std::cerr << "caught: " << e.what() << '\n'; // never reached
}
}go deeper
Know that throwing from a destructor while another exception is propagating always ends the program.
Explain that noexcept(false) only matters on normal scope exit and that unwinding plus an escaping exception is a listed std::terminate case.
Implement the construction-time uncaught_exceptions comparison correctly, explain why the singular function was removed, and prefer an explicit flush or commit API.
Decide whether the codebase allows throwing destructors at all; most teams forbid them and accept logged failures on cleanup paths.
## What happens When an exception is thrown, C++ **unwinds the stack**: as control passes from the `throw` to the handler, it destroys every automatic object constructed since the `try` block was entered, in reverse order. Each of those destructors runs while an exception is already propagating. The standard lists, among the situations that call `std::terminate`, the case "when the destruction of an object during stack unwinding terminates by throwing an exception". This rule is independent of the destructor's exception specification: | Destructor | Throws on normal scope exit | Throws during unwinding | |---|---|---| | implicit `noexcept(true)` | `std::terminate` | `std::terminate` | | `noexcept(false)` | the exception propagates normally | `std::terminate` | The snippet below makes the inventory's `AuditLog` throw from a `noexcept(false)` destructor while an "insert failed" exception is propagating. The program prints `in flight: 1` and libc++ terminates with `uncaught exception of type std::runtime_error: audit flush failed`; the matching handler never runs. ## Why the language cannot do better Two exceptions would be in flight at once, and C++ has no way to propagate two. Picking one silently would lose the other, and the destructor's failure usually means the program's state is already in doubt, so the standard chooses to stop. ## Detecting unwinding with `std::uncaught_exceptions` `std::uncaught_exceptions()` (C++17) returns the number of exceptions in the current thread that have been thrown but not yet caught. The pattern that relies on it: 1. In the constructor, store `int in_flight_ = std::uncaught_exceptions();`. 2. In the destructor, compare: if `std::uncaught_exceptions() > in_flight_`, the object is being destroyed by unwinding, so record the failure and return without throwing. 3. Otherwise this is a normal scope exit, and throwing is allowed for a `noexcept(false)` destructor. The **comparison with the stored value** matters. A count above zero alone is wrong, because an object can be created and destroyed normally inside a destructor that is itself running during unwinding; the count is already nonzero for its whole life. That is exactly why the singular `std::uncaught_exception()`, which returned only a `bool`, was superseded by the plural function in C++17 and removed in C++20; the standard's compatibility annex says it did not have a clear specification when multiple exceptions were active. This is the mechanism behind "scope guard" helpers that run one action on success and another on failure. ## Scope guards built on the count The same comparison powers small helpers that run code at scope exit depending on how the scope ended: - a **success guard** runs its action only when the count did not grow, for example committing a transaction log entry; - a **failure guard** runs its action only when it did, for example rolling back a reservation in the inventory; - an **exit guard** always runs, like a plain RAII wrapper. Such guards keep their destructors non-throwing by catching inside them, so they gain the information without taking on the risks of a throwing destructor. ## The design most teams prefer The counting trick works, but it keeps a throwing destructor in the codebase, with all its costs: containing types become potentially throwing to destroy, and generic code that requires `std::is_nothrow_destructible_v<T>` rejects the type. The usual alternative: - Give the class an explicit **`flush()`** or **`commit()`** that can throw and that callers invoke on the success path. - Keep the destructor **non-throwing**: if `flush()` was not called, it tries to flush inside `try { ... } catch (...)` and logs a failure. - Treat a failure detected only in the destructor as a defect to fix, not a normal error path. ## Related terminate cases worth naming The same family of rules calls `std::terminate` when a destructor of an object with static or thread storage duration exits via an exception, when an `atexit` handler throws, and when copying an exception object into a handler parameter throws. All share one cause: the exception mechanism or the shutdown sequence is already running and has nowhere to send a second error. ## Checklist - No destructor in shared code should be `noexcept(false)` without a documented reason. - Any destructor that must throw on normal exit uses `std::uncaught_exceptions()` compared with its construction-time value. - Fallible cleanup is exposed as an explicit member function.
- Why is checking std::uncaught_exceptions() > 0 in the destructor not enough?An object can live entirely inside code that runs during unwinding, for example a helper created inside another object's destructor. The count is nonzero for that helper's whole life, so a `> 0` test would make it think it is being unwound when it is exiting normally. Comparing with the count stored at construction tells the two apart, which is what the C++17 plural function was added for.
- Does catching inside the destructor avoid the terminate during unwinding?Yes. The terminate case is an exception *escaping* the destructor during unwinding. A destructor may throw and catch internally as much as it likes while unwinding is in progress; `try { flush(); } catch (...) { log(); }` inside the destructor is the standard non-throwing pattern.
- noexcept(false) lets a destructor throw safely during unwinding.
- The second exception replaces the first one during unwinding.
- std::uncaught_exceptions() > 0 is enough to detect unwinding in a destructor.
- std::uncaught_exception() is the current way to check for unwinding.
Assumes C++17 or later for std::uncaught_exceptions; the singular std::uncaught_exception was removed in C++20.