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:
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.