MiddleDebuggingVery commonNot answered yet
What happens if a destructor throws during stack unwinding?
This program throws, and during the resulting cleanup Bad's destructor also throws. Instead of reaching any handler, the process aborts abruptly.
struct Bad {
~Bad() noexcept(false) { throw std::runtime_error("dtor"); }
};
void demo() {
Bad b;
throw std::logic_error("first");
}
Identify the bug and explain the cause.
If a destructor lets an exception escape while another exception is already being unwound, the program calls std::terminate().
- ✗Marking a destructor noexcept(false) and relying on callers to catch it
- ✗Throwing from cleanup code while another exception is active
- ✗Putting important error reporting only into a destructor
- →What does std::uncaught_exceptions() report?
- →How do standard library containers use noexcept move constructors?
Destructors are implicitly noexcept since C++11. If a destructor lets an exception escape while another exception is already being unwound, the runtime cannot decide which of the two to propagate and calls std::terminate():
struct Bad {
~Bad() noexcept(false) { throw std::runtime_error("dtor"); }
};
void demo() {
Bad b; // b's destructor runs during unwinding
throw std::logic_error("first"); // starts unwinding → ~Bad() throws a second
} // two live exceptions → std::terminate()
Rule: destructors must not throw. Wrap any cleanup that can fail in a try/catch inside the destructor itself and swallow or log the error.