📄 demo_exception_handling_1.cpp
字号:
//****************************************************
// 三角形条件的异常检测
//****************************************************
//# include <iostream.h>
//# include <math.h>
# include <iostream>
# include <cmath>
using namespace std;
double triangle(double,double,double);
int main()
{
cout<<"begin of main()"<<endl;
cout<<endl;
double a,b,c,area;
cout<<"input three sides of triganle: ";
cin>>a>>b>>c;
//try块进行异常检测:检测以下语句中的函数调用是否产生异常
//引发异常后跳出try语句体,控制转向catch语句
//try块之后必须是花括号复合语句,即使只有一个语句
try
{
while(a>0 && b>0 && c>0)
{
area=triangle(a,b,c);
cout<<"area of triangle is: "<<area<<endl;
cout<<endl;
cout<<"input three sides of triganle: ";
cin>>a>>b>>c;
}
}
//不允许在try块和catch之间插入任何其它语句
// cout<<"Throw exception and await process ..."<<endl;
//被检测到的异常被catch捕获并作相应处理
//try块之后必须是花括号复合语句,即使只有一个语句
catch(double)
{
cout<<"a="<<a<<",b="<<b<<",c="<<c<<": that is not a traingle!"<<endl;
}
cout<<endl;
cout<<"end of main()"<<endl;
return 0;
}
double triangle(double a,double b,double c)
{
cout<<"begin of triangle()"<<endl;
double s=(a+b+c)/2,area;
//当引发一个异常时,抛出异常信息
//同时,不再执行函数随后语句,控制返回到调用程序
// if(a+b<=c||b+c<=a||c+a<=b) throw a; //异常类型为double
if(a+b<=c||b+c<=a||c+a<=b) throw 1.0; //OK! double类型
//注意: 类型匹配过程不作任何类型转换,下面都是错误的情况:
//若找不到类型匹配catch异常处理块:编译连接没问题,但执行错误,
//提示: abnormal program termination
// if(a+b<=c||b+c<=a||c+a<=b) throw 1.0f; //异常类型为float
// if(a+b<=c||b+c<=a||c+a<=b) throw 1; //异常类型为int
// if(a+b<=c||b+c<=a||c+a<=b) throw 1L; //异常类型为long int
area=sqrt(s*(s-a)*(s-b)*(s-c));
cout<<"end of triangle()"<<endl;
return area;
}
/*
begin of main()
input three sides of triganle: 3 4 5
begin of triangle()
end of triangle()
area of triangle is: 6
input three sides of triganle: 1 2 1
begin of triangle()
a=1,b=2,c=1: that is not a traingle!
end of main()
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -