先看如下代码
//可抛出所有类型异常
void TestFunction01(){
throw 10;
}
int main(){
try{
TestFunction01();
}
catch (...){
cout << "捕获异常!" << endl;
}
system("pause");
return EXIT_SUCCESS;
}
在TestFunction01()中,可以抛出任何的异常类型,那么现在我提一个需求,如何让TestFunction01()中只抛出double类型呢?
方式很简单,只需要在TestFunction01()中添加throw关键字,具体如下
//可抛出所有类型异常
void TestFunction01() throw(double){
throw 10;
}
int main(){
try{
TestFunction01();
}
catch (...){
cout << "捕获异常!" << endl;
}
system("pause");
return EXIT_SUCCESS;
}
再次运行程序,你会发现,会弹出程序终止的弹框。因为throw 10 抛出的是int 类型,TestFunction01()只允许抛出double类型的数据。在测试的时候,要再Qt或是Linux中才可以观察到序终止的效果,要是在vs2013中,TestFunction01()拦截不了抛出的异常,程序依然能捕获到异常,这是因为不同的系统平台,编译器对TestFunction01()后的throw 解读不同。