/*
test2
try catch throw c++的异常处理机制的简单程序
处理除数遇到0的例子
*/
test2
try catch throw c++的异常处理机制的简单程序
处理除数遇到0的例子
*/
#include<iostream>
#include <iomanip>
using namespace std;
namespace Test2
{
class test
{
public:
double fuc(double &, double &);
};
double test::fuc(double &x, double &y)
{
if (y == 0)
{
throw "There is a quetion";//---引发异常
}
double c;
c = x / y;
return c;
}
}
int main()
{
using namespace Test2;
test test1;
double a, b;
while (true)
{
cout << "请输入除数和被除数:\n";
cin >> a >> b;
try//-----------try里面是可能引发异常代码块
{
cout << setprecision(3)<<test1.fuc(a, b) << endl;
}
catch (const char * str)//---接收异常,处理异常
{
cout << str << endl;
break;
}
}
return 0;
}
本文介绍了一个使用C++编写的简单程序,演示了如何通过try-catch语句处理除法运算中出现的除数为零的情况。程序定义了一个名为test的类,其中包含一个成员函数fuc用于执行除法,并在遇到除数为零时抛出异常。
794

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



