【发布时间】:2015-03-06 14:22:51
【问题描述】:
我正在通过 Stroustrup 的 PP&P Using C++ 学习 c++,我已经到第五章了:“事实上,在 std_lib_fa cilities.h 中,我们提供了一个默认情况下终止程序的 error() 函数带有系统错误消息以及我们作为参数传递给 error() 的字符串。”
这是我的代码:
#include "../../std_lib_facilities.h";
class Neg_sqrt{};
void sqr (double a, double b, double c)
{
if ((b*b - 4*a*c) < 0)
throw Neg_sqrt();
double x1 = 0, x2 = 0;
x1 = (-b + sqrt(b*b - 4*a*c))/(2*a);
x2 = (-b - sqrt(b*b - 4*a*c))/(2*a);
cout << "Roots of given equation are\n" << x1 << " and " << x2 << endl;
}
int main()
try
{
double a = 0, b = 0, c = 0;
cout << "Enter floating point parameters of quadratic equation: a, b and c\n";
cin >> a >> b >> c;
sqr(a,b,c);
}
catch (Neg_sqrt)
{
error("Sqrt of negative value is not defined!");
}
Error() 只是终止程序,它不显示发送给它的字符串。为什么是这样?此外,#include "std_lib_facilities.h" 可以在这里找到:http://www.stroustrup.com/Programming/std_lib_facilities.h
【问题讨论】:
-
使用的库中的相关函数好像是:
inline void error(const string& s) { throw runtime_error(s); } -
好吧,您从 main 中的
catch块中抛出,但您永远不会捕获error(...)抛出的异常。该程序只是终止,不需要打印任何内容。 -
所以我的错误信息不应该显示在任何地方?我完全误解了那部分?
标签: c++ error-handling runtime-error