Search code examples
c++exceptiontry-catchin-class-initialization

How the try / catch in initialization list works?


We consider that an exception in initialization may happen. So we write try / catch block.

int f(){
    throw 1;
}

class A
{
public:
    A() try : _k(f())
    {}
    catch (int)
    {
        std::cout << "Exception 1" << std::endl;
    }

private:
    int _k;
};

But the catch rethrows exception on one level deeper. Thats means that next code

try
{
    A a;
} catch(int)
{
    std::cout << "Exception 2" << std::endl;
}

will output:

Exception 1
Exception 2

Why this try / catch block behaves not the same way as ordinary try / catch block?

Full code example: http://ideone.com/XjY2d


Solution

  • It seems your question is: Why does a function-level try/catch automatically rethrow the exceptoin? With throwing an exception from a the construction of an object, this object is considered dead before it comes to life. All its subobjects are destroyed. That is, if an exception is thrown during construction there is no object. If the exception would not throw, you'd get a hull of an object into your hands. This is clearly not desirable.