P
P
proydakov2014-04-25 17:50:30
C++ / C#
proydakov, 2014-04-25 17:50:30

How to catch multiple exceptions in destructors when inheriting?

#include <iostream>
#include <stdexcept>

class A
{
public:
    A()
    {
        std::cout << "A" << std::endl;
        fake();
    }

    virtual ~A()
    {
        throw std::runtime_error("Test ex in ~A()");
        std::cout << "~A" << std::endl;
    }

    void fake()
    {
        d();
    }

    virtual void d()
    {
        std::cout << "A::d()" << std::endl;
    }
};

class B : public A
{
public:
    B()
    {
        std::cout << "B" << std::endl;
        fake();
    }

    ~B()
    {
        std::cout << "~B" << std::endl;
    }

    virtual void d()
    {
        std::cout << "B::d()" << std::endl;
    }
};

class C : public B
{
public:
    C()
    {
        std::cout << "C" << std::endl;
        fake();
    }

    ~C()
    {
        throw std::runtime_error("Test ex in ~C()");
        std::cout << "~C" << std::endl;
    }

    virtual void d()
    {
        std::cout << "C::d()" << std::endl;
    }
};

int main( int argc, char *argv[] )
{
    try {
        {
            C object;
        }
    }
    catch (const std::exception& e) {
        std::cout << "catch: " << e.what() << std::endl;
    }

    return 0;
}

The output is:
Starting /home/evgeny/develop/build-testcpp-Desktop_Qt_5_2_1_GCC_64bit-Debug/testcpp...
A
A::d()
B
B::d()
C
C::d()
~B
terminate called after throwing an instance of 'std::runtime_error'
what(): Test ex in ~A()
The program terminated unexpectedly.
/home/evgeny/develop/build-testcpp-Desktop_Qt_5_2_1_GCC_64bit-Debug/testcpp has crashed
How to catch all exceptions?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lolshto, 2014-04-25
@proydakov

And because it is not necessary to release exceptions from the destructor - it is necessary to catch all of them in the same place.
Specifically in your case - if an exception is thrown from the destructor while another exception is being handled, the application will terminate.
stackoverflow.com/questions/130117/throwing-except...

X
xandox, 2014-04-25
@xandox

Well, for starters: calling virtual functions in a base class constructor is just as bad as having children. Not handling possible exceptions in the destructor is even worse.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question