Question

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

Was it helpful?

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.

OTHER TIPS

The object you're constructing has not really been constructed, so simple return is not an option. This kind of try0-catch always rethrows (unless you throw your own exception from catch clause).

Because it is not an ordinary try-catch block but a function-level try/catch. It automatically rethrows unless you do it explicitly by using throw.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top