c++中的异常处理定义和使用方法

发布时间:2020-08-11 00:08:06 作者:岩枭
来源:网络 阅读:301

异常处理:

所谓异常处理就是指对运行时出现的差错以及其它例外情况的处理。

C++中处理异常的机制由3部分组成:检查(try),抛出(throw),捕捉(catch)。

c++中的异常处理定义和使用方法c++中的异常处理定义和使用方法c++中的异常处理定义和使用方法c++中的异常处理定义和使用方法

1:求三角形的面积。

程序:

#include<iostream>

#include<cmath>

using namespace std;


double triangle(double a, double b, double c)//定义求三角形面积的函数

{

double s = (a + b + c) / 2;

if (a + b <= c || a + c <= b || b + c <= a)

{

throw a;//不符合三角形条件抛出异常信息a

}

return sqrt(s*(s - a)*(s - b)*(s - c));

}


int main()

{

double triangle(double, double, double);

double a, b, c;

cin >> a >> b >> c;

try//在try块中包括要检查的函数

{

while (a > 0 && b > 0 && c > 0)

{

cout << triangle(a, b, c) << endl;

cin >> a >> b >> c;

}

}

catch (double)//用catch捕捉异常信息并作相应处理

{

cout << "a=" << a << ",b=" << b << ",c=" << c << ",that is not a triangle!" << endl;

}

cout << "end" << endl;

system("pause");

return 0;

}

结果:

6 5 4

9.92157

1 2 1

a=1,b=2,c=1,that is not a triangle!

end

请按任意键继续. . .

在函数嵌套下检查异常处理。

程序:

#include<iostream>

using namespace std;


void f1()

{

void f2();

try

{

f2();

}

catch (char)

{

cout << "ERROR1!";

}

cout << "end1" << endl;

}


void f2()

{

void f3();

try

{

f3();

}

catch (int)

{

cout << "ERROR2!" << endl;

}

cout << "end2" << endl;

}


void f3()

{

double a = 0;

try

{

throw a;//抛出double类型异常

}

catch (float)

{

cout << "ERROR3!" << endl;

}

cout << "end3" << endl;

}


int main()

{

void f1();

try

{

f1();

}

catch (double)

{

cout << "ERROR0!" << endl;

}

cout << "end0" << endl;

system("pause");

return 0;

}

结果:

ERROR0!

end0

请按任意键继续. . .

注意:

a.如果将f3函数的catch子句改为catch (double)程序中其它部分不变,则f3函数中的throw抛出的异常信息立即被f3函数的catch子句捕获,因为抛出的是double型异常信息,输出“ERROR3!”,再执行catch子句后面的语句,输出“end3”。F3函数执行结束后,流程返回f2函数,继续往下执行。运行结果:

ERROR3!

end3

end2

end1

end0

请按任意键继续. . .

b.若f3函数的catch子句改为:

catch (double)

{

cout << "ERROR3!" << endl;

throw;

}

f3函数中的throw抛出的异常信息a,被f3函数的catch子句捕获,输出“ERROR3!”,但它即用“throw;”将a再抛出,于是a被main函数中的catch子句捕获。

运行输出:

ERROR3!

ERROR0!

end0

请按任意键继续. . .


推荐阅读:
  1. C++ 中的异常处理(五十三)
  2. Java中异常处理的使用方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

检查 异常处理 函数嵌套

上一篇:Mysql导入导出几种方式+查看修改数据库字符集方法

下一篇:语音直播系统开发,一套完整的语音直播系统源码必有的特色功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》