Q:

Detecting when destructor running due to exception being thrown?

What is a good way in C++ to detect in a destructor that it is being run during unwind of the stack due to an exception being thrown as opposed to a normal exit of scope triggering the destructor?  I'd like to know so that I can create a class that has some cleanup code that is always run on normal exit but skipped when an exception occurs.

A:

std::uncaught_exception() (defined in <exception>) will tell you in your destructor if it was called because of an exception:
class A
{
public:
    ~A()
    {
        if (std::uncaught_exception()) {
            // Called because of an exception
        } else {
            // No exception
        }
    }
};

A:

Probably this article will help you. The article will show you the problems with std::uncaught_exception() and contains an advice how to deal with exceptions in destructors.

