In C++, how can I detect in the body of my destructor whether the stack is being unwound due to an exception being thrown? Once detected, can I get a reference to the active exception?
I ask because I'd like to add some debugging code that explains why a certain situation may arise and whether it is due to exceptions or not.
std::uncaught_exception
tells you whether the stack is being unwound due to an exception being thrown, which is what you asked.
However, it doesn't tell you what you probably want to know: whether the object whose destructor you call it from, is in the part of the stack that's being unwound, or the part of the stack that's being destroyed normally due to non-exceptionally exiting a scope beneath some other destructor that is part of the unwind:
struct A {
~A();
};
struct B {
~B();
}
int main() {
try {
A a;
throw 1;
} catch(...) {}
}
A::~A() {
std::uncaught_exception(); // true
B b;
}
B::~B() {
std::uncaught_exception(); // also true, but "b" isn't being "unwound",
// because ~A() returned, it didn't throw.
}
Contrary to what DeadMG and Xeo say, you cannot get a reference to an exception that has not been caught. throw
with no operand rethrows the "currently handled exception", that is to say an exception whose catch-handler you are in, or whose catch-handler has called you. It does not rethrow an uncaught exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With