In C++, what exception specification does a destructor get when you write none, and what happens if it throws?
answer
- changed in C++11
- computed from subobject destructors
- usually noexcept(true)
- terminate, not propagate
basics
~10 sSince C++11 a destructor without a noexcept specifier is non-throwing unless the destructor of a base or member is potentially throwing. So a throw that escapes it calls std::terminate instead of reaching any handler.
solid answer
~40 sA destructor declared without a `noexcept`-specifier, implicitly or by the user, gets a computed exception specification: it is potentially throwing only if a destructor of one of its potentially constructed subobjects (bases and members), or of a virtual base, is. For ordinary classes that makes it `noexcept(true)`, and `std::is_nothrow_destructible_v<T>` is `true`. A `throw` that escapes it therefore ends in `std::terminate`, even inside a `try` whose handler would match. Clang warns: `'~ReservationGuard' has a non-throwing exception specification but can still throw [-Wexceptions]`. C++03 code that threw from destructors changed meaning in C++11. To let one escape you must write `noexcept(false)`, and the standard library's own destructors never throw, while a throwing destructor of a type you hand to the library is undefined behaviour unless that component allows it.
code
cpp · 19 lines#include <iostream>
#include <stdexcept>
#include <type_traits>
struct ReservationGuard {
~ReservationGuard() { // no specifier: implicitly noexcept
throw std::runtime_error("release failed");
}
};
static_assert(std::is_nothrow_destructible_v<ReservationGuard>);
int main() {
try {
ReservationGuard g;
} catch (const std::exception& e) { // never reached
std::cerr << "caught: " << e.what() << '\n';
}
}go deeper
Remember that destructors are noexcept by default and that throwing from one ends the program.
Explain how the implicit specification is computed from bases and members, why C++11 changed it, and how std::is_nothrow_destructible reports it.
Move fallible cleanup into explicit close or commit functions, keep destructors as non-throwing safety nets, and catch inside destructors that call fallible code.
Ban noexcept(false) destructors in shared code, because the property propagates to every containing type and breaks library assumptions.
## The rule The C++ standard gives destructors special treatment in the exception-specification rules. A function declared without a `noexcept`-specifier is normally potentially throwing, **unless it is a destructor**, a deallocation function, or a special member defaulted on its first declaration. For a destructor, implicitly declared or user-written, without a specifier: - it is **potentially throwing** if any destructor of its potentially constructed subobjects (direct bases, non-static data members) is potentially throwing, or if the destructor is virtual and a virtual base's destructor is potentially throwing; - otherwise it is **non-throwing**, the same as `noexcept(true)`. Since every standard library destructor behaves as if it were `noexcept`, and most user types contain only standard types and scalars, the computed answer is nearly always `noexcept(true)`. ## What a throwing destructor does Because the specification is non-throwing, an exception that tries to leave the destructor hits the same rule as any `noexcept` function: the handler search would exit a non-throwing function, so **`std::terminate` is called**. The surrounding `try` block never gets a chance. In the snippet below the inventory's `ReservationGuard` throws from its destructor at the end of a `try` block, and the `catch` that would match is never entered. Clang flags it at compile time: ```plaintext warning: '~ReservationGuard' has a non-throwing exception specification but can still throw [-Wexceptions] note: destructor has a implicit non-throwing exception specification ``` ## Why C++11 made this the default In C++03 a destructor without an exception specification could throw. C++11 changed that, and the standard's compatibility annex records the consequence: valid C++03 code may execute differently, because destructors that throw now call `std::terminate`. The reasons: 1. **Destructors run during unwinding**, and a second exception escaping a destructor while one is already propagating has no sane outcome. 2. **The standard library relies on it.** Containers destroy elements in `clear()`, `erase()` and their own destructors, which are specified not to throw; a throwing element destructor would make those promises impossible. 3. **Optimisation.** Knowing destructors do not throw can let compilers omit unwinding paths around them. ## Opting out, and why you rarely should You can write `~AuditLog() noexcept(false)` and the exception will propagate normally when the destructor runs during ordinary scope exit. The costs: - If the same destructor throws **during stack unwinding**, `std::terminate` is called anyway. - Members and bases of every class containing your type become potentially-throwing to destroy too, because the rule propagates upward. - `std::is_nothrow_destructible_v` becomes `false`, and generic code that requires non-throwing destruction rejects the type. Worse, the standard library makes it undefined behaviour when a destructor operation of a type it works with exits via an exception, unless the library component specifically allows it. ## How the property spreads The computed specification makes a throwing destructor contagious. Given `struct Flaky { ~Flaky() noexcept(false); };`, a class `Holder` with a `Flaky` member and a user-written `~Holder() {}` gets a **potentially-throwing** destructor, although nobody wrote `noexcept(false)` on it, and `std::is_nothrow_destructible_v<Holder>` is `false`. Any class holding a `Holder`, or deriving from it, inherits the same property. One `noexcept(false)` deep in a library can therefore turn off non-throwing destruction for a large part of a codebase without a visible change in the code that is affected. ## How destructors should report failure instead | Approach | How it works | |---|---| | Explicit `close()` / `commit()` | a member function that can throw; the destructor only cleans up if it was not called | | Log and swallow | the destructor catches inside itself and records the failure | | Error member | the destructor stores a status the owner can query earlier | The common pattern is the first: `file.close()` reports errors to code that can handle them, and the destructor is a non-throwing safety net. ## Checking it - `static_assert(std::is_nothrow_destructible_v<T>);` in a class's header documents and enforces the property. - Build with clang's default warnings and keep `-Wexceptions` on; it catches direct throws in destructors. - A destructor that calls a function that may throw needs a `try`/`catch (...)` inside it.
- Can a class's destructor be potentially throwing without anyone writing noexcept(false) on it?Yes. Its computed specification is potentially throwing if a base or member destructor is, so a member of a type with `~Member() noexcept(false)` makes the containing class's destructor potentially throwing too. The property spreads upward through composition, which is one reason to keep `noexcept(false)` destructors out of shared code.
- What should a destructor do when its cleanup call can fail?Catch inside the destructor and record the failure, and offer an explicit member function, such as `close()` or `commit()`, that callers use when they need to see the error. The destructor then calls the cleanup only if the explicit call did not happen, inside `try { ... } catch (...) { /* log */ }`, so nothing escapes.
- A destructor without noexcept can throw like any other function.
- A try block around the object's scope catches what its destructor throws.
- Writing noexcept(false) makes throwing destructors safe during unwinding.
- Destructors became noexcept by default in C++17.