C++异常接口声明和使用详解try catch throw

来源:互联网 发布:数据库基础教程 推荐 编辑:程序博客网 时间:2024/05/21 20:23

C++异常接口声明和使用详解try catch throw

发布人:cctwL 文章来源: 关注次数:445


若有异常则通过throw操作创建一个异常对象并抛掷。
将可能抛出异常的程序段嵌在try块之中。控制通过正常的顺序执行到达try语句,然后执行try块内的保护段。
如果在保护段执行期间没有引起异常,那么跟在try块后的catch子句就不执行。程序从try块后跟随的最后一个catch子句后面的语句继续执行下去。
catch子句按其在try块后出现的顺序被检查。匹配的catch子句将捕获并处理异常(或继续抛掷异常)。
如果匹配的处理器未找到,则运行函数terminate将被自动调用,其缺省功能是调用abort终止程序。
经典例题:

#include<iostream.h>
int Div(int x,int y);
void main()
{ try
{ cout<<"5/2="<<Div(5,2)<<endl;
cout<<"8/0="<<Div(8,0)<<endl;
cout<<"7/1="<<Div(7,1)<<endl;
}
catch(int)
{ cout<<"except of deviding zero.\n"; }
cout<<"that is ok.\n";
}
int Div(int x,int y)
{ if(y==0) throw y; //这里必须throw 否则就错误而捕获不到异常
return x/y;
}

注意:
C++ try catch 没有finally 有 catch(...)
必须有 trow 才能捕获

异常接口声明:
可以在函数的声明中列出这个函数可能抛掷的所有异常类型。
例如: void fun() throw(A,B,C,D);
若无异常接口声明,则此函数可以抛掷任何类型的异常。
不抛掷任何类型异常的函数声明如下:
void fun() throw();

使用方法:

int Div(int x,int y) ;
void main()
{ try
{ cout<<"5/2="<<Div(5,2)<<endl;
cout<<"8/0="<<Div(8,0)<<endl;
cout<<"7/1="<<Div(7,1)<<endl;
}
catch(int)
{ cout<<"except of deviding zero.\n"; }
cout<<"that is ok.\n";
system("pause");
}
int Div(int x,int y) throw() //这里限定运行抛出异常
{
throw(3); //这里却抛出了整形的异常。 所以编译就通不过去。如果没有上面异常接口限定本题正确通过
return x/y;
}

原文链接“http://hi.baidu.com/feng20068123/blog/item/0652dbcd2bb47c2bb700c852.html

原创粉丝点击