方法1
#include<iostream> //包含头文件
#include<stdlib.h>
using namespace std;
double fuc(double x, double y) //定义函数
{
if(y==0)
{
throw y; //除数为0,抛出异常
}
return x/y; //否则返回两个数的商
}
void main()
{
double res;
try //定义异常
{
res=fuc(2,3);
cout<<"The result of x/y is : "<<res<<endl;
res=fuc(4,0); //出现异常
}
catch(double) //捕获并处理异常
{
cerr<<"error of dividing zero.\n";
}
system("pause");
}
方法2
#include<iostream> //包含头文件
#include<stdlib.h>
using namespace std;
double fuc(double x, double y) //定义函数
{
if(y==0)
{
cout<<"error of dividing zero.\n"; //除数为0,抛出异常
return y;
}
return x/y; //否则返回两个数的商
}
void main()
{
double res;
res=fuc(2,3);
cout<<"The result of x/y is : "<<res<<endl;
res=fuc(4,0); //出现异常
system("pause");
}
大家谈谈这两个处理有何看法 |