How to catch an exception from a member destructor

I wonder if it is possible (and how) to catch the exception created in the destructor of the participant. 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?
    }
};
+4
source share
2 answers

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

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

However, you cannot do much with such an exception. The standard states that you cannot access the elements of a non-static element or the base classes of an object B.

In addition, you cannot disable the exception. Unlike other functions, the exception will be thrown implicitly as soon as the handler of the try-block function of the destructor (or constructor) finishes execution.

, .

+5

, :

#include <stdexcept>
#include <iostream>

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

class B
{
    A _a;
public:
    ~B() noexcept(false) try {
        // dtor body
    }
    catch (std::exception const& e)
    {
        std::cout << "~B: " << e.what() << std::endl;
        // rethrown and you can't do anything about it
    }
};

int main()
{
    try
    {
        B b;
    }
    catch (std::exception const& e)
    {
        std::cout << "main: " << e.what() << std::endl;
    }
}

, ++ ( n3376) 15.3. :

15 , -try-block .

+2

All Articles