c catch oracle异常处理,c++中的异常处理 - memristor的个人空间 - OSCHINA - 中文开源技术交流社区...

异常

当程序检测到一个它无法处理的问题就需要用到异常处理。检测出问题的部分应该发出某种信号表示程序碰到了故障,信号发出方无需知道故障将在何处解决。

try

{

//程序中抛出异常

throw value;

}

catch(valuetype1 v)

{

//例外处理程序段

}

catch(valuetype2 v)

{

//例外处理程序段

}

throw抛出值,catch接受

异常执行流程

1、执行try语句块的保护段

2、如果保护段执行期间没有异常,跟在try语句后面的catch子句就不会执行,从最后一个catch后跟随的语句执行下去

3、如果有异常被throw,按照顺序检查catch类型。

4、没有找到匹配的处理器,运行terminate函数,调用abort终止程序

5、找到匹配的处理器,捕获值,创建异常对象,一旦程序开始执行异常处理代码,沿着函数调用链创建的对象(调用析构函数)将被销毁。

#include

using namespace std;

int main(){

char myarray[10];

try {

for (int n=0; n<=10; n++) {

if (n>9) throw "Out of range";

myarray[n]='z';

}

} catch (const char * str) {

cout <

}

try

{

throw 1;

throw "error";

}

catch(char *str)

{

cout <

}

catch(int i)

{

cout <

}

return 0;

}

程序输出为:

Exception: Out of range

1

C++标准库的异常类层次结构

C++标准库中的异常层次的根类被称为exception,定义在库的头文件中

exception类的接口

namespace std //注意在名字空间域std中

{

class exception

{

public:

exception() throw() ; //默认构造函数

exception(const exception &) throw() ; //复制构造函数

exception &operator=(const exception&) throw() ;

//复制赋值操作符

virtual ~exception() throw() ; //析构函数

virtual const char* what() const throw() ;

//返回一个C风格的字符串,目的是为抛出的异常提供文本描述

};

}

Exception classes

This header defines a set of standard exceptions that both the library and programs can use to report common errors.

They are divided in two sets:

Logic errors

Runtime errors

对整数,溢出指代数值:小于最小值为下溢,大于最大值为上溢

对浮点数,溢出指绝对值:绝对值小于浮点数所能表示的最小值,为下溢,当作 0;绝对值大于浮点数所能表示的最大范围,为上溢,当作 INF

根据具体符号的不同,又分为:正上溢、正下溢、负上溢、负下溢

自己定义异常类

#include 

#include 

using namespace std;

//可以自己定义Exception

class myexception: public exception

{

virtual const char* what() const throw()

{

return "My exception happened";

}

}myex;

int main () {

try

{

if(true)    //如果,则抛出异常;

throw myex;

}

catch (exception& e)

{

cout <

}

return 0;

}

继承exception覆盖what函数

程序输出

My exception happened

异常处理后还能继续运行之后的代码吗?

一个异常没有被捕获,它将终止当前的程序,如果被捕获了,则从最后一个catch后面的第一条语句开始继续执行

#include

using namespace std;

int div(int x, int y)

{

if(y==0) throw 0;

return x/y;

}

int main()

{

int m,n;

try

{

cout<

cin>>m>>n;

cout<

}

catch(int)

{

cout<

}

//cout<<1/0<

cout<

return 0;

}

如果cout<<1/0;系统将终止,如果放在异常处理块中,还能继续运行

捕获所有异常

#include

using namespace std;

void f(int);

void f(int x)

{

try

{

if(x>0)

{

throw 0;

}

if(x==0)

{

throw 'a';

}

if(x<0)

{

throw 1.1;

}

}

catch(int)

{

cout<0"<

}

//    catch(char)

//    {

//        cout<

//    }

//    catch(double)

//    {

//        cout<

//    }

catch(...)

{

cout<

}

}

int main()

{

f(1);

f(-1);

f(0);

return 0;

}

output

x>0

unknown error!

unknown error!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值