use*_*043 12 c++ constructor exception
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;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
0x32c88 exception A
0x32c88 exception A
Run Code Online (Sandbox Code Playgroud)
由于异常已经在构造函数中被捕获B,为什么它仍然出现在main函数中?
CB *_*ley 21
当contol流到达构造函数的function-try-block的处理程序的末尾时,将自动重新抛出捕获的异常.
您无法抑制在派生类构造函数中构造基类或成员期间抛出的异常,因为这会导致构造的派生对象具有未能构造的基础或成员.
这个GOTW是相关的:http://www.gotw.ca/gotw/066.htm
来自ISO/IEC 14882:2011 15.3 [except.handle]/15:
如果控制到达构造函数或析构函数的function-try-block的处理程序的末尾,则重新抛出当前处理的异常.[...]
| 归档时间: |
|
| 查看次数: |
616 次 |
| 最近记录: |