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?
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. [...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With