Middle+
What happens if an exception is thrown from a destructor?
sobes.tech AI
Answer from AI
Throwing an exception from a destructor leads to undefined behavior in C++. If during stack unwinding due to another exception, a destructor is called that also throws an exception, the program will terminate abnormally (usually by calling std::terminate). This situation is called a "double fault".
Therefore, exceptions should be avoided in destructors.
Possible approaches to error handling in destructors:
- Catch any exceptions inside the destructor and ignore them or log an error message.
- Use a status flag within the object to make the destructor behave differently depending on whether the object is in a valid state.
- Provide a separate
closeorreleasemethod that the user must call before destroying the object. This method can throw exceptions and perform actions that might fail. The destructor in this case should simply release resources without performing potentially failing operations.
Example of catching an exception in a destructor:
#include <iostream>
#include <stdexcept>
class MyClass {
public:
~MyClass() {
try {
// Actions that might throw an exception
// For example, closing a file, logging, etc.
if (true) { // Simulate an error condition
throw std::runtime_error("Exception from destructor");
}
} catch (const std::exception& e) {
// Catch and handle the exception
// For example, log it
std::cerr << "Exception in destructor: " << e.what() << std::endl;
// Do not rethrow
}
}
};
int main() {
try {
MyClass obj;
// Other code that might throw an exception
// throw std::runtime_error("First exception"); // Uncomment to demonstrate double fault without try/catch in destructor
} catch (const std::exception& e) {
std::cerr << "Caught first exception: " << e.what() << std::endl;
}
// 'obj' is destroyed when exiting main scope or after exception handling above
return 0;
}