#include "stdafx.h"
#include <iostream>
#include<stdlib.h>
#include <stdio.h>
using namespace std;
double fuc(double x, double y) //定义函数
{
if(y==0)
{
throw y; //除数为0,抛出异常
}
return x/y; //否则返回两个数的商
}
void main()
{
double res=0;
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";
exit(1); //异常退出程序
}
}
#include <iostream>
#include<stdlib.h>
#include <stdio.h>
using namespace std;
double fuc(double x, double y) //定义函数
{
if(y==0)
{
throw y; //除数为0,抛出异常
}
return x/y; //否则返回两个数的商
}
void main()
{
double res=0;
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";
exit(1); //异常退出程序
}
}
本文详细阐述了如何在C++中通过自定义函数实现数学运算,并且运用异常处理机制确保程序的健壮性和鲁棒性,具体展示了当除数为零时如何优雅地抛出异常并进行错误提示。
1万+

被折叠的 条评论
为什么被折叠?



