Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
    }
};
like image 272
Lukáš Bednařík Avatar asked Mar 22 '16 14:03

Lukáš Bednařík


People also ask

Can we call an exception from destructor?

Throwing an exception out of a destructor is dangerous. If another exception is already propagating the application will terminate.

What happens if an exception is thrown in the destructor?

Destructors are only called for the completely constructed objects. When the constructor of an object throws an exception, the destructor for that object is not called.

How can I handle a destructor that fails?

How can I handle a failure in the destructor.? A failure in the constructor can be handled by throwing an exception, where as throwing an exception in the destructor will lead to stack unwinding.

How do you handle exceptions that arise in constructors explain with an example?

You would catch the exception in the calling code, not in the constructor. Exceptions aren't returned in the same way as return values, they skip up the stack to the first appropriate catch block, so whilst you can't return a value from the constructor you can throw an exception from it.


1 Answers

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.

like image 164
Angew is no longer proud of SO Avatar answered Sep 18 '22 15:09

Angew is no longer proud of SO