C ++ 函数后面加throw()的作用
2015-09-09 09:07
330 查看
Following declaration gives a message to the user of your class: my method
doesn't throw any exception. Don't bother to put a try/catch block around it
when you use it.
void A::foo() throw();
It's your responsibility not to throw an exception in the definition of your
method.
Say
void A::foo() throw() {
throw (5); // you are doomed here.
}
The compiler won't give an error on above code. But you will get a run time
error (your program aborts) if you implemented it this way.
/////////////////////////////////
成员函数声明后面跟上throw(),表示告诉类的使用者:我的这个方法不会抛出异常,所以,在使用该方法的时候,不必把它至于 try/catch 异常处理块中。
声明一个不抛出异常的函数后,你有责任保证在你的函数的实现里面不会抛出异常。
void A::foo() throw() {
throw (5); // 程序会在这里崩溃.(编者注:如果该异常被处理,不会崩溃)
}
编译器不会认为上面的代码存在错误,(编者注:vc2005会给出警告:warning C4297: “foo”: 假定函数不引发异常,但确实发生了)但是,如果该异常未被上层的异常过滤器捕捉的话,会引发运行时的错误。
/////////////////////////////////
综上述:
1) 函数后面声明 throw() 只是接口的提供者和接口的使用者间的默契或称协议。
2) 这种协议不影响正常的异常处理流程。
3) vc2005 会在编译器对这种协议的遵守情况进行检查,并在为遵守协议的情况下 给出警告。
同理, 函数后面可以跟上 throw( int ),表示该函数可能会抛出 int型的异常。但不会抛出别的类型的异常。使用者应该注意捕获 该函数可能抛出的int型的异常
文章转自:http://blog.csdn.net/zdl1016/article/details/4204025
doesn't throw any exception. Don't bother to put a try/catch block around it
when you use it.
void A::foo() throw();
It's your responsibility not to throw an exception in the definition of your
method.
Say
void A::foo() throw() {
throw (5); // you are doomed here.
}
The compiler won't give an error on above code. But you will get a run time
error (your program aborts) if you implemented it this way.
/////////////////////////////////
成员函数声明后面跟上throw(),表示告诉类的使用者:我的这个方法不会抛出异常,所以,在使用该方法的时候,不必把它至于 try/catch 异常处理块中。
声明一个不抛出异常的函数后,你有责任保证在你的函数的实现里面不会抛出异常。
void A::foo() throw() {
throw (5); // 程序会在这里崩溃.(编者注:如果该异常被处理,不会崩溃)
}
编译器不会认为上面的代码存在错误,(编者注:vc2005会给出警告:warning C4297: “foo”: 假定函数不引发异常,但确实发生了)但是,如果该异常未被上层的异常过滤器捕捉的话,会引发运行时的错误。
/////////////////////////////////
综上述:
1) 函数后面声明 throw() 只是接口的提供者和接口的使用者间的默契或称协议。
2) 这种协议不影响正常的异常处理流程。
3) vc2005 会在编译器对这种协议的遵守情况进行检查,并在为遵守协议的情况下 给出警告。
同理, 函数后面可以跟上 throw( int ),表示该函数可能会抛出 int型的异常。但不会抛出别的类型的异常。使用者应该注意捕获 该函数可能抛出的int型的异常
文章转自:http://blog.csdn.net/zdl1016/article/details/4204025
相关文章推荐
- 升级win10、安装visual studio 2015、学习C#
- 福利到~分享一个基于jquery的智能提示控件intellSeach.js
- 浅谈java实现重载的方法
- android自定义弹出框样式实现
- MAC下QT5 + Xcode 4.6.3 使用小结
- SOAPUI测试REST项目(八)——REST功能测试
- git 使用
- C#设计模式(2)——简单工厂模式
- SOAPUI测试REST项目(七)——REST请求工作
- 【读书笔记】iOS-自动释放池
- 【位运算经典应用】 N皇后问题
- android开发 如何调用SO
- tomcat部署web项目的3中方法
- Android常用工具类
- 【读书笔记】iOS-自动释放池
- IOS中 Block简介与用法(一)
- Studio之widget类型及继承于Wiget类型控件的事件-----监听各个GUI控件的交互事件。
- 我的Android进阶之旅------>(全解析)屏幕尺寸,分辨率,像素,PPI之间到底什么关系?
- SOAPUI测试REST项目(六)——REST服务和WADL
- oracle 由易到难源代码三