当前位置:首页 > 通信资讯 > 正文

C++抛出异常(c++ 构造函数抛出异常)

如果我们编写了一个函数,函数内部可能会出现异常,但是我们不想在这个函数内处理,而是想要通知调用者,那么C++允许它重抛出这个异常。语法如下:

?
1 2 3 4 5 6 try { //Execute some code } catch (Exception& e) { //Peform some operations before exits throw; }

语句throw重新抛出了异常。

看一个实际的例子:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 #include <iostream> #include <stdexcept> using namespace std; int f(){ try{ throw runtime_error("Exception in f"); } catch(exception& e){ cout << "Exception caught in f" << endl; cout << e.what() << endl; throw; } } int main() { try{ f(); } catch(exception& e){ cout << "Exception caught in main" << endl; cout << e.what() << endl; } return 0; }

运行结果:

C++抛出异常(c++ 构造函数抛出异常)

知识点扩展

c++重新抛出异常
有可能单个catch不能完全处理一个异常,此时在进行了一些处理工作之后,需要将异常重新抛出,由函数调用链中更上层的函数来处理。重新抛出由“throw;”语句实现,throw后不跟表达式或类型。

“throw;”将重新抛出异常对象,它只能出现在catch或catch调用的函数中,如果出现在其它地方,会导致调用terminate函数。

被重新抛出的异常是原来的异常对象,不是catch形参。该异常类型取决于异常对象的动态类型,而不是catch形参的静态类型。比如来自基类类型形参catch的重新抛出,可能实际抛出的是一个派生类对象。

只有当异常说明符是引用时,在catch中对形参的改变,才会传播到重新抛出的异常对象中。

?
1 2 3 4 5 6 7 catch (my_error & eObj) { eObj.status = severeErr; throw; // the status member of the exception object is severeErr } catch (other_error eObj) { eObj.status = badErr; throw; // the status member of the exception rethrown is unchanged }

以上就是C++异常重抛出实例分析的详细内容,更多关于C++异常重抛出的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/bwjblogs/p/12826726.html

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。