0

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
bibbsey
  • 969
  • 2
  • 9
  • 14

1 Answers1

2

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.

Tomek
  • 4,554
  • 1
  • 19
  • 19
  • If base/member subobject construction fails, you can't possibly complete construction of the derived object. Ergo, the exception is rethrown automatically. – Casey Jul 11 '13 at 18:50
  • And that's what I intended to explain. – Tomek Jul 11 '13 at 18:52