Sobes.tech
Junior — Middle

What consequences can occur if an exception is thrown in a destructor?

sobes.tech AI

Answer from AI

If an exception is thrown in a destructor, and another exception is already being processed at the time of object destruction (for example, during stack unwinding), this will lead to a call to std::terminate() and the program will terminate abnormally.

The reason is that C++ does not allow two exceptions to propagate simultaneously from the same thread. Therefore:

  • Exceptions in destructors should either not be thrown at all.
  • Or they should be caught within the destructor and handled (for example, logged), preventing them from escaping.

Example of a safe destructor:

~MyClass() {
    try {
        // code that may throw an exception
    } catch (...) {
        // handle the exception to prevent it from escaping
    }
}