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
- C++异常接口声明和使用详解try catch throw
- 【c#】异常处理:try catch throw
- java异常 try-catch 和throw
- try catch throw 使用
- try catch 和 throw
- 异常(try-throw-catch)
- try catch throw异常处理
- try,catch,throw异常捕捉
- 异常处理 throw try catch
- 异常处理 try catch throw
- C/C++编程异常处理中try和throw以及catch语句的用法
- Java 异常处理 try catch finally throws throw 的使用和解读(一)
- C++中的异常捕获与处理:Try、Throw、Catch关键字的理解和使用
- java中异常的使用try{}catch(){}finally{} ;throw。
- java异常处理之throw, throws,try和catch
- Java中抛出异常try...catch和throw简易区别
- java异常处理之throw, throws,try和catch
- Java初学习-异常处理 throw, throws,try和catch
- Windows环境下的tomcat + apache配置(绝对实践操作版)
- BT源代码学习心得(四):种子文件的生成 -- 转贴自wolfenstein (NeverSayNever)
- 下拉框鼠标悬停显示内容
- Android模拟器无法上网
- BT源代码学习心得(五):统一网络服务接口--RawServer -- 转贴自 wolfenstein (NeverSayNever)
- C++异常接口声明和使用详解try catch throw
- Response.Redirect(),Server.Transfer(),Server.Execute()的区别
- JCL中SORT的应用
- GLSL学习笔记
- BT源代码学习心得(六):跟踪服务器(Tracker)的代码分析(初始化) -- 转贴自 wolfenstein (NeverSayNever)
- LCD-Framebuffer驱动实现
- BT源代码学习心得(七):跟踪服务器(Tracker)的代码分析(HTTP协议处理对象) -- 转贴自 wolfenstein (NeverSayNever)
- 使用wscript对象实现注册表操作
- Android View如何获取焦点