-
自定义异常类并且抛出
#include<iostream>
using namespace std;
#include<string>
class CException
{
public:
string msg;
CException(string s) :msg(s) {}
};
double Devide(double x,double y)
{
if (y == 0)
throw CException("devided by zero");
return x / y;
}
int main()
{
double x, y;
cin >> x >> y;
try
{
while(true)
{
cout << Devide(x,y) << endl;
cin >> x >> y;
}
}
catch (CException e)
{
cout << e.msg << endl;
}
}
-
直接throw异常
#include<iostream>
using namespace std;
double Devide(double x,double y)
{
if (y == 0)
throw "Error:Division by 0";
return x / y;
}
int main()
{
double x, y;
cin >> x >> y;
try
{
while(true)
{
cout << Devide(x,y) << endl;
cin >> x >> y;
}
}
catch (const char* msg)
{
cout << msg << endl;
}
}