异常机制
异常机制
try块(可能异常的代码块) catch块(捕获异常) throw块(引发异常)
//////////////////////////////////////
//
//error.cpp
//
///////////////////////////////////////
#include <iostream>
double hmean(double a,double b);
int main(void)
{
using namespace std;
double x,y,z;
cout<<"enter two number: ";
while (cin>>x>>y)
{
try //try
{
z=hmean(x,y);
}
catch (const char * s) //catch
{
cout<<s<<endl;
cout<<"enter a new pair of numbers: ";
continue;
}
cout<<"mean of "<<x<<" and "<<y<<" is "<<z<<endl;
cout<<"enter next set of numbers <q to quit>: ";
}
cout<<"bye!\n";
return 0;
}
double hmean(double a,double b)
{
if (a==-b)
throw "bad hmean() arguments: a=-b not allowed"; //throw
return 2.0*a*b/(a+b);
}


浙公网安备 33010602011771号