【问题标题】:Exception is caught twice异常被捕获两次
【发布时间】:2012-07-20 07:43:34
【问题描述】:
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的构造函数中被捕获了,为什么它还在main函数中出现?

【问题讨论】:

    标签: c++ exception constructor


    【解决方案1】:

    当contol的流程到达构造函数的function-try-block的处理程序末尾时,捕获的异常将自动重新抛出。

    您不能抑制在派生类构造函数中构造基类或成员期间引发的异常,因为这会导致构造的派生对象的基类或成员构造失败。

    此 GOTW 相关:http://www.gotw.ca/gotw/066.htm

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多