异常被捕获两次

Exception is caught twice

本文关键字:两次 异常      更新时间:2023-10-16
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;
}

输出为:

0x32c88 exception A
0x32c88 exception A

既然异常已经在B的构造函数中被捕获,为什么它仍然出现在主函数中?

当 contol 流到达构造函数的函数尝试块的处理程序末尾时,捕获的异常将自动重新引发。

不能禁止在派生类构造函数中构造基类或成员

期间引发的异常,因为这将导致构造派生对象具有构造失败的基或成员。

这个GOTW是相关的:http://www.gotw.ca/gotw/066.htm

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

如果控件到达构造函数或析构函数的函数 try-block 的处理程序的末尾,则会重新引发当前处理的异常。[...]