What happens when a destructor throws
3 days ago
- #Exception Handling
- #RAII
- #C++
- Since C++11, destructors are implicitly noexcept(true), so throwing from one by default calls std::terminate.
- If explicitly marked noexcept(false), a destructor can throw when no other exception is active, allowing the exception to propagate and be caught.
- If a destructor throws during stack unwinding from another exception, even if noexcept(false), std::terminate is always called, as per the C++ standard.
- The conventional advice is to avoid throwing from destructors; instead, use logging or error flags for error handling.
- The author highlights that many developers, including senior candidates, are unaware of the behavior and dangers of throwing destructors.