c++destructorfunction-try-block

How to catch exception from member destructor


I wonder whether (and how) it's possible to catch an exception thrown in a member destructor. Example:

#include <exception>

class A
{
public:
    ~A() {
        throw std::exception("I give up!");
    }
};

class B
{
    A _a;
public:
    ~B() {
        // How to catch exceptions from member destructors?
    }
};

Solution

  • Yes, you can catch such an exception, using the function-try-block:

    class B
    {
        A _a;
    public:
        ~B() try {
            // destructor body
        }
        catch (const std::exception& e)
        {
            // do (limited) stuff
        }
    };
    

    However, you cannot really do much with such an exception. The standard specifies that you cannot access non-static data members or base classes of the B object.

    Also, you cannot silence the exception. Unlike with other functions, the exception will be re-thrown implicitly once the function-try-block handler of a destructor (or constructor) finishes execution.

    All in all, destructors should really not throw exceptions.