henryyao
henryyao

Reputation: 1818

why my exception from a destructor is not caught

class D
{
public:
    ~D() { throw std::exception(); }
};
int main()
{
    try
    {
        try
        {
            D d;
        }
        catch (...)
        {
            cout << "1";
        }
    }
    catch (std::exception& e)
    {
        cout << "2";
    }
}

My understating is that this should be caught in 2. But its not caught, and instead program is terminated.

Upvotes: 1

Views: 466

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155313

In C++11, destructors are implicitly noexcept, so std::terminate is called automatically if the destructor throws an exception that isn't caught within the destructor itself.

Even before that, destructors that throw an uncaught exception during stack unwinding cause std::terminate to be invoked, so what you're doing won't work if the destructor is invoked by some other exception bubbling up the stack.

If that's not a concern, you can explicitly declare your destructor to be ~D() noexcept(false) (which would allow exceptions to bubble out of the destructor if the destructor wasn't triggered by some other exception causing stack unwinding).

Note that even though it's technically legal, it's generally considered a bad idea to throw uncaught exceptions in a destructor, since it makes your class largely unusable in any context where a handleable exception might be thrown. You can read more at c++ exception in destructor (which isn't a strict duplicate, but covers your scenario completely).

Upvotes: 7

Related Questions