我正在处理下面的代码,弄糊涂了,请看一下。
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
void Xhandler(int test) throw(char,double) /*i am restricting an integer exception here by not including it in the argument list of throw*/
{
if(test==0) throw test;
if(test==1) throw 'a';
if(test==2) throw 123.23;
}
int main()
{
cout<"start";
try{
Xhandler(0);
}
catch(int i) /*this catch statement must be ignored then,but it is running*/
{
cout<<"caught an integer"; /*this is the output on the screen*/
}
catch(char c)
{
cout<<"caught character";
}
catch(double a)
{
cout<<"caught double";
}
cout<<"end";
_getch();
return 0;
}对应于int的catch语句必须被忽略(不能被忽略)&程序必须终止,因为没有留下匹配的catch语句,但不是这样吗?
发布于 2011-08-01 03:48:41
您没有指定编译器。如果您使用的是Microsoft visual C++,在MSDN上的Exception Specifications page处有一条注释。
ANSI C++在实现异常规范时与
标准不同。下表总结了异常规范的可视化C++实现:
..。
throw( type ) -函数可以抛出类型为type的异常。但是,在Visual C++ .NET中,这被解释为抛出(...)。
使用g++时,由于运行示例时出现意外异常,进程将终止。
发布于 2011-08-01 04:11:12
好吧,原因是
catch(int i) /*this catch statement must be ignored then,but it is running*/
{
cout<<"caught an integer"; /*this is the output on the screen*/
}执行异常处理程序,而不是调用意外的处理程序,可能是由您的编译器决定的。
当具有异常规范的函数抛出异常,但抛出的异常的类型与异常规范不匹配时,标准的一致行为将是调用意外的处理程序。缺省处理程序终止程序。
实际上,许多编译器会忽略异常规范,一些编译器可能只是发出一些警告来告诉你这一点。编译器忽略它们是个好主意。
C++中的异常规范不会以您希望的方式工作。异常规范并不意味着编译器保证除了异常规范中提到的异常之外,函数不能抛出任何其他异常。在标准一致的编译器中,这只是意味着编译器必须在运行时强制执行异常规范(如果抛出的异常与异常规范匹配,则没有问题,如果不匹配,则应在意外处理程序中结束)
关于异常规范的更多信息,以及为什么你应该避免它们,请参见here (Herb Sutter在那里解释说,C++中的异常规范大多不是它们应该是的/大多数人认为它们是什么)。你会在页面底部找到更多的链接...
发布于 2011-08-01 04:11:23
您的Xhandler例程在声明不会抛出int异常后抛出int异常。这是未定义的,所以任何事情都可能发生。
https://stackoverflow.com/questions/6891748
复制相似问题