打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C++中的异常规范
 

C++中的异常规范

分类: MFC 44人阅读 评论(0) 收藏 举报

以前在网上看到有人问函数后面加throw()的用处。
今天在C++PRIMER中看到了异常规范一章,总结一下吧。
理论书上已经讲得很清楚,咱就直接上代码实践一把吧。

代码均用g++(3.4.2版本)编译,微软的cl编译器会出现不同结果,估计是用非标准C++的结果。
首先定义一个简单的异常类
===============================
#include<string>
using namespace std;
class myException
{
public:
myException(string err):_msg(err){}
~myException(){}
string dump(){return _msg;}
private:
string _msg;
};
===============================
定义三个函数分别能抛出myException,string异常,string异常,和不会抛出异常
在C++PRIMER中:
void f1(int whitch) throw(myException, string); //保证不会抛出myException, string之外的异常
void f2() throw(string); //保证不会抛出string之外的异常
void f3() throw(); //保证不会抛出任何异常
见下面的代码:
=================================================
#include"exception.h"

void f1(int whitch) throw(myException, string);
void f2() throw(string);
void f3() throw();

int main()
{
try
{
   f3();
}
catch(string& e)
{
   cout<<e<<endl;
}
catch(myException& e)
{
   cout<<e.dump()<<endl;
}
catch(...)
{
   cout<<"other err"<<endl;
}
return 0;
}
void f1(int whitch) throw(myException, string)
{
if( 0 == whitch )
{
   throw myException("this myException from f1");

}
else
{
   throw string("this stringException from f1");
}
}
void f2() throw(string)
{
f(1);
throw string("this stringException from f2");
}
void f3() throw()
{
f2();
}
===========================================================

运行结果:
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

分析:f2中的string异常,在f2内部没有处理,抛出到f3中,而f3中也没有处理,需要继续向上抛,但是f3保证不抛出异常。到此产生运行时错误。系统调用terminate函数,而terminate会调用about终止程序。
为验证以上分析结果,去掉f3后面的throw,编译运行,得到结果:this stringException from f2

=============================================================
在f2中调用f1抛出一个string的异常:
=================================
void f2() throw(string)
{
f1(1);
throw string("this stringException from f2");
}
=================================
运行结果:
this stringException from f1
================================
在f2中调用f1抛出一个myException类型的异常:
=================================
void f2() throw(string)
{
f1(0);
throw string("this stringException from f2");
}
=================================
运行结果:
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

分析:由于f1中抛出的是一个myException的异常,而f2只能够抛出string型的异常。所以这个myException没有地方处理,故系调用terminate函数终止程序。
=================================

结论:
1、函数后面的throw()用于指定该函数可以抛出的异常,括号中指定异常类型,若为空则说明不允许抛出异常。若不限定异常类型,则不要加throw().
2、没有在函数声明中声明的异常,不能够从函数体中抛出,必须在本函数中捕获并处理。
3、函数中没有被捕获的异常会继续向上抛,直到main函数中,若还没有被处理,则系统调用terminate终止进程。

看着不错转过来!

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
异常机制及throw与throws的区别
异常
c++标准库——错误和异常处理 - 闻道有先后
有关JAVA异常和错误(ERROR)的处理
java常用类解析七:java异常机制、异常栈、异常处理方式、异常链、异常丢失
C 异常概念详解 - 51CTO.COM
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服