People have argued pretty strongly against throwing exceptions from destructors. Take this answer as an example. I wonder whether std::uncaught_exception() can be used to portably detect whether we are in the process of unwinding the stack due to some other exception.

I find myself deliberately throwing exceptions in destructors. To mention two possible use cases:

  • Some resource cleanup which involves flushing buffers, so that failure likely signifies truncated output.
  • Destruction of an object holding a std::exception_ptr which might contain an exception encountered in a different thread.

Simply ignoring these exceptional situations feels plain wrong. And chances are that by throwing an exception some exception handler might be able to provide more useful context information than if the destructor itself were writing to std::cerr. Furthermore, throwing exceptions for all failed assertions is an important part of my unit testing approach. An error message followed by an ignored error condition wouldn't work in that case.

So my question is, is it OK to throw exceptions except when another exception is being processed, or is there a reason not to do that?

To put this in code:

Foo::~Foo() {
  bool success = trySomeCleanupOperation();
  if (!success) {
    if (std::uncaught_exception())
      std::cerr << "Error in destructor: " << errorCode << std::endl;
    else
      throw FooOperationFailed("Error in destructor", errorCode);
  }
}

As far as I can tell, this should be safe and in many cases better than not throwing an exception at all. But I'd like to verify that.

Edit
Report