Sobes.tech
Junior — Middle

What happens if an unhandled exception occurs in a destructor?

sobes.tech AI

Answer from AI

In C++, if an unhandled exception occurs in a destructor, and at the same time another exception is being processed (for example, the destructor is called during exception handling), then std::terminate() is invoked, which leads to the program terminating abnormally.

This is because C++ does not allow simultaneous handling of two exceptions (an exception during the processing of another exception). Therefore, it is recommended to avoid throwing exceptions from destructors. If an error might occur in a destructor, it is better to handle it inside the destructor or use try-catch blocks to prevent the exception from propagating outward.

Example of a safe destructor:

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