1.try{}函数体内是用来检查的部分。
try
{
x1=p+q(a,b,c);
x2=p-q(a,b,c);
cout<<x1<<' '<<x2<<' '<<"try"<<endl;
}
2.如果检查到try中有错误就会抛出信息,用throw关键字来抛出。
double q(double a,double b,double c)
{
double x,d;
d=b*b-4*a*c;
if(d<0)throw d; //如果出现错误,就会执行throw
return sqrt(d)/2*a;
return x/(2*a);
}
3.抛出了throw之后,程序就会直接跳转到抓捕环节,用catch关键字来表示。
catch(double d)
{
cout<<a<<' '<<b<<' '<<c<<' '<<d<<"error!"<<endl;
}
举例:
完整含try-throw代码:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double q(double ,double ,double );
double a,b,c,p,x1,x2;
cin>>a>>b>>c;
p=-b/(2*a);
try
{
x1=p+q(a,b,c);
x2=p-q(a,b,c);
cout<<x1<<' '<<x2<<' '<<"try"<<endl;
}
catch(double d)
{
cout<<a<<' '<<b<<' '<<c<<' '<<d<<"error!"<<endl;
}
cout<<endl;
return 0;
}
double q(double a,double b,double c)
{
double x,d;
d=b*b-4*a*c;
if(d<0)throw d; //如果出现错误,就会执行throw
return sqrt(d)/2*a;
return x/(2*a);
}
当输入错误数据时:
可以看到只出现了,抓捕环节的数据,没有try函数体中的cout输出。
当输入正确数据时:
可以发现,抓捕环节的cout没有执行,因为输入数据正确。