Search code examples
c++exceptiondestructorraii

Detecting active exceptions in the destructor


I have a class that is using RAII for cleanup in case something goes wrong. This means the class contains a flag, that tells it whether the work has been completed, and if this flag is not set when the constructor is called it is performing it's cleanup tasks and produces a log messages. Now I would like this class to become one step more clever, i.e. it should find out, if the error happened, because the work was abborted (i.e. an exception was thrown and the destructor got called) or because someone was missusing this class and never actually finished the work. This means I would have to find out in the destructor, if an exception is active. If one is found I would produce a log message, possibly printing the content of the exception and then rethrowing it. I am guessing something like this.

Foo::~Foo () {
  try { /* do not know what to put here */ }
  catch( const std::exception & ex ) {
     // produce error in log
     throw;
  }
  catch( ... ) {
    // produce some other log message
    throw;
   }
}

However I am not sure if this would work at all, since the exception is active already before the destructor is called and does not originate from the try block. Also I am using a throw; inside the destructor and throwing an exception at this point is a really bad Idea. So I would not do it, unless the standard guarantees clearly that this case is an exception (no pun intended) to this rule (which I don't know).

So is this possible at all, or should I handle this situation in some other way?


Solution

  • There was no way to use bool std::uncaught_exception() correctly, so it was removed in C++20. We now have int std::uncaught_exceptions().

    You need to call it twice: once beforehand (e.g. in the constructor), then again in the destructor. If the second call returned a larger number, it means the destructor was called due to an exception. Otherwise it will return the same number.

    struct A
    {
        int e = std::uncaught_exceptions();
    
        ~A()
        {
            if (std::uncaught_exceptions() > e)
                // An exception was thrown.
        }
    };