bibbsey
bibbsey

Reputation: 1029

Exception handled in constructor propagated back. How?

I have a class whose constructor will throw an exception. I also have a catch block to handle that exception. But still, I see that the exception is propagated back to the caller even though it is handled. I know, there should be an exception to inform the caller that construction failed. But in this case how does it (re-throw) happen?

class Test
{
    public:
        Test()
        try
        {
            std::cout << "in child constructor" << std::endl;
            throw 3.2;
        }
        catch(int &e)
        {
            std::cout << "in int catch: " << e << std::endl;
        }
        catch (double &e)
        {
            std::cout << "in double catch: " << e << std::endl;
        }
};

int main (void)
{
    try
    {
        Test obj;
    }
    catch (int &e)
    {
        std::cout << "in main int catch: " << e << std::endl;
    }
    catch (double &e)
    {
        std::cout << "in main double catch: " << e << std::endl;
    }

    return 0;
}

The output I got is

in child constructor
in double catch: 3.2
in main double catch: 3.2

Upvotes: 0

Views: 246

Answers (1)

Tomek
Tomek

Reputation: 4659

This is correct according to standard. Section 15.3, point 15 of n3337.pdf reads:

The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor. Otherwise, a function returns when control reaches the end of a handler for the function-try-block (6.6.3). Flowing off the end of a function-try-block is equivalent to a return with no value; this results in undefined behavior in a value-returning function (6.6.3).

You can fully catch and prevent an exception from propagating inside constructor/destructor body. You cannot however catch the exceptions thrown from base class/member constructors/destructors this way.

Upvotes: 2

Related Questions