C++异常接口声明和使用详解try catch throw
2012-07-20 10:50
323 查看
C++异常接口声明和使用详解try catch throw
发布人:cctwL 文章来源: 关注次数:445![](http://hiphotos.baidu.com/s_icily/pic/item/ba1b7159d109b3de4ee7d7dcccbf6c81810a4c85.jpg)
若有异常则通过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
相关文章推荐
- 异常处理(try catch throw)详解(C++)
- C++中的异常捕获与处理:Try、Throw、Catch关键字的理解和使用
- C++异常处理:try,catch,throw,finally的用法
- 从零开始学C++之异常(一):C语言错误处理方法、C++异常处理方法(throw, try, catch)简介
- 从零开始学C++之异常(一):C语言错误处理方法、C++异常处理方法(throw, try, catch)简介
- C++中异常处理的语法 try catch throw
- C++ try catch() throw 异常处理
- [置顶]C++异常处理:try,catch,throw,finally的用法
- paip.提升用户体验---gcc c++ try catch不能捕获异常的解决--使用 SEH Ca6
- C++中异常处理try-throw-catch
- C++中异常处理的语法 try catch throw
- C++处理异常技巧-try,catch,throw,finally
- C++ try catch() throw 异常处理
- C++使用try&catch进行异常处理的简单范例
- 二十一天学通C++之使用try/catch捕获异常
- C++ 异常处理:try、catch、throw、异常规格申明
- C++异常处理:try,catch,throw,finally的用法
- c++初级 之 异常处理trycatchthrow
- 二十一天学通C++之使用try/catch捕获异常
- C++中try/catch/throw的使用