以前在网上看到有人问函数后面加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终止进程。
看着不错转过来!
联系客服