C++异常处理分析

1.源代码

例1

#include
#include
using namespace std;
double f1(double x,double y,double
z);//计算三角形面积函数 
int main()
{
double a,b,c,s;
cout<<"请输入三角形三边长:";
cin>>a>>b>>c;
do
{
if(a>0&&b>0&&c>0)
{
s=f1(a,b,c);
if(s!=0)
{
cout<<s<<endl;
cout<<"请输入三角形三边长:";
cin>>a>>b>>c;
}
}
else
{
cout<<"输入的数据有误!";
cout<<"请输入三角形三边长:";
cin>>a>>b>>c;
s=1;
}
}while(s!=0);
return 0;
} 
double f1(double x,double y,double
z)//计算三角形面积函数 
{
double s;
s=(x y z)/2;
if(x y<=z||x z<=y||y z<=x)
{
cout<<"a="<<x<<"b="<<y<<"c="<<z<<"三边无法构成三角形!"<<endl;
return 0;
}
else
{
return(sqrt(s*(s-x)*(s-y)*(s-z)));
}
}

例2

#include
#include
using namespace std;
double f1(double x,double y,double
z);//计算三角形面积函数 
int main()
{
double a,b,c;
cout<<"请输入三角形三边长:";
cin>>a>>b>>c;
try
{
while(a>0&&b>0&&c>0)
{
cout<<f1(a,b,c)<<endl;
cout<<"请输入三角形三边长:";
cin>>a>>b>>c;
}
}
catch(double)
{
cout<<"a="<<a<<"b="<<b<<"c="<<c<<"三边无法构成三角形!"<<endl;
}
return 0;
} 
double f1(double x,double y,double
z)//计算三角形面积函数 
{
double s;
s=(x y z)/2;
if(x y<=z||x z<=y||y z<=x)throw x;
return(sqrt(s*(s-x)*(s-y)*(s-z)));
}

例3

#include
#include
using namespace std;
int main()
{
void f1();
try
{
f1();
}
catch(double)
{
cout<<"ERRORO!"<<endl;
}
cout<<"endl0"<<endl;
return 0;
} 
void f1()//计算面积函数 
{
void f2();
try
{
f2();
}
catch(char)
{
cout<<"ERROR1!"<<endl;
}
cout<<"endl1"<<endl;
}
void f2()//计算面积函数 
{
void f3();
try
{
f3();
}
catch(int)
{
cout<<"ERROR2!"<<endl;
}
cout<<"endl2"<<endl;
}
void f3()//计算面积函数 
{
double a=0;
try
{
throw a;
}
catch(double)
{
cout<<"ERROR3!"<<endl;
}
cout<<"endl3"<<endl;
}

2.运行截图

图1
在这里插入图片描述
图2
在这里插入图片描述
图3
在这里插入图片描述

3.分析总结

例3是一个典型的C 处理错误的例子,主函数调用f1,f1再调用f2,f2在调用f3,
在f3中发现错误,先在f3中查找判断有没有法处理,发现无法处理则返回它的上一级 f2,
接着在f2中查找判断有没有法处理,发现无法处理则返回它的上一级 f1,
再接着在f1中查找判断有没有法处理,发现无法处理则返回它的上一级 main函数,
接着在main中查找判断有没有法处理,发现有法处理则处理错误。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值