Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception is caught twice

class A{
    public:
        A() { throw string("exception A"); };
};

class B{
    A a;
    public:
        B() try : a() {} catch(string& s) { cout << &s << " " << s << endl; };
};

int main(){    
    try{
        B b;
    }catch(string& s){
        cout << &s << " " << s << endl;
    }
    return 0;
}

The output is:

0x32c88 exception A
0x32c88 exception A

Since the exception was already caught in the constructor of B, why it still occur in the main function?

like image 381
user1540043 Avatar asked Jul 20 '12 07:07

user1540043


1 Answers

When the flow of contol reaches the end of the handler for a function-try-block of a constructor, the caught exception will automatically be re-thrown.

You cannot suppress an exception thrown during the construction of a base class or member in a derived class constructor as this would lead to a constructed derived object with a base or member that had failed to be constructed.

This GOTW is relevant: http://www.gotw.ca/gotw/066.htm

From ISO/IEC 14882:2011 15.3 [except.handle] / 15:

The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor. [...]

like image 83
CB Bailey Avatar answered Sep 29 '22 12:09

CB Bailey