Junior — Middle
Is it possible to generate an exception inside a destructor and how would it affect the program's operation?
sobes.tech AI
Answer from AI
Generating an exception inside a destructor in C++ is not recommended. If an exception is thrown from a destructor during the handling of another exception (for example, when exiting a try block), it will lead to a call to std::terminate and terminate the program.
This is because it is unsafe to throw new exceptions during exception unwinding — it creates a double exception situation.
If you need to signal an error in a destructor, it is better to use other mechanisms, such as logging or returning a status through separate methods, but not throwing exceptions directly.
Example of bad practice:
struct A {
~A() {
throw std::runtime_error("Error in destructor"); // dangerous!
}
};
Such code can lead to program crash.