异常被捕获两次 [英] Exception is caught twice

查看:209
本文介绍了异常被捕获两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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例外A 
0x32c88例外A

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

解决方案

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



在构造一个派生类构造函数的基类或成员时,你无法压制一个异常,因为这将导致一个构造的派生对象,其中包含一个无法构造的基础或成员。 p>

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



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


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



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. [...]

这篇关于异常被捕获两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆