2023.10.14
异常捕获
以try,catch,throw三个关键字为组合,try中为可能会出现异常的代码,throw为出现异常后返回的内容,catch为如何处理返回的内容
throw返回字符串
#include <iostream>
#include <cstdlib>
using namespace std;
double hmean(double x, double y);
int main()
{
double a, b, c;
cout << "Pls input two number:";
while (cin >> a >> b)
{
try
{
c = hmean(a, b);
}
catch (const char *s)
{
cout << endl
<< s << endl
<< "Enter a new pair of number:" << endl;
continue;
}
cout << "Harmonic mean of " << a << " and " << b << " is " << c << endl
<< "Enter a new pair of number(q to quit):" << endl;
}
cout << "Bye!" << endl;
return 0;
}
double hmean(double x, double y)
{
if (x == -y)
throw "bad hmean() arguments:x = -y is not allowed!";
return 2.0 * x * y / (x + y);
}
throw返回对象
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
class bad_hmean
{
private:
double v1;
double v2;
public:
bad_hmean(double a = 0, double b = 0) : v1(a), v2(b) {}
void mesg();
};
inline void bad_hmean::mesg()
{
cout << "hmean(" << v1 << " , " << v2 << "):invalid arguments:a = -b\n";
}
class bad_gmean
{
public:
double v1;
double v2;
bad_gmean(double a = 0, double b = 0) : v1(a), v2(b) {}
const char *mesg();
};
inline const char *bad_gmean::mesg()
{
return "gmean() arguments should be >= 0\n";
}
double hmean(double x, double y);
double gmean(double x, double y);
int main()
{
double a, b, c;
cout << "Pls input two number:";
while (cin >> a >> b)
{
try
{
c = hmean(a, b);
cout << "Harmonic mean of " << a << " and " << b << " is " << c << endl
<< "Enter a new pair of number(q to quit):" << endl;
cout << "Geometric mean of " << a << " and " << b << " is " << gmean(a, b) << endl
<< "Enter a new pair of number(q to quit):" << endl;
}
catch (bad_hmean &bg)
{
bg.mesg();
cout << "Try again.\n";
continue;
}
catch (bad_gmean &hg)
{
cout << hg.mesg();
cout << "Value used: " << hg.v1 << " ," << hg.v2 << endl;
cout << "Sorry, you don't get to play any more.\n";
break;
}
}
cout << "Bye!" << endl;
return 0;
}
double hmean(double x, double y)
{
if (x == -y)
throw bad_hmean(x, y);
return 2.0 * x * y / (x + y);
}
double gmean(double x, double y)
{
if (x < 0 || y < 0)
throw bad_gmean(x, y);
return sqrt(x * y);
}