Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect whether an exception is active during destructor?

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.

like image 495
WilliamKF Avatar asked Feb 23 '23 13:02

WilliamKF


1 Answers

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.

like image 72
Steve Jessop Avatar answered Feb 25 '23 03:02

Steve Jessop