Why is this an issue?
When an exception is thrown, the call stack is unwound up to the point where the exception is to be handled. The destructors for all automatic
objects declared between the point where the exception is thrown and where it is to be handled will be invoked. If one of these destructors exits with
an exception, then the program will terminate in an implementation-defined manner, potentially yielding unexpected results.
Note that it is acceptable for a destructor to throw an exception that is handled within the destructor, for example within a try-catch block.
Noncompliant code example
class C1 {
public: ~C1() {
throw(42); // Noncompliant - destructor exits with an exception
}
};
void foo() {
C1 c; // program terminates when c is destroyed
throw(10);
}
Compliant solution
class C1 {
public: ~C1() {
try {
throw(42); // Compliant - exception will not leave destructor
} catch (int i) { // int handler
// Handle int exception throw by destructor
}
}
};
void foo() {
C1 c;
throw(10);
}
Resources
- MISRA C++:2008, 15-5-1 - A class destructor shall not exit with an exception.