【问题标题】:error("some string") only shows error, not error + stringerror("some string") 只显示错误,不显示错误+字符串
【发布时间】: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&amp; s) { throw runtime_error(s); }
  • 好吧,您从 main 中的 catch 块中抛出,但您永远不会捕获 error(...) 抛出的异常。该程序只是终止,不需要打印任何内容。
  • 所以我的错误信息不应该显示在任何地方?我完全误解了那部分?

标签: c++ error-handling runtime-error


【解决方案1】:

函数error(const std::string&amp;) 抛出异常。异常要么在某处被捕获,要么将终止程序。在您的情况下,error("...") 中的 std::runtime_error 不会被捕获。因此,程序简单地终止(一旦发生这种情况就不需要打印任何内容,尽管大多数操作系统会打印一条类似于“调用 std::terminate 后程序退出的消息”)。

您应该做的(如果您实际上不想抛出可能在更高级别捕获的不同异常)只是打印错误:

[...]
catch ( Neq_sqrt )
{
   std::cerr << "Sqrt of negative value is not defined!\n";
}

【讨论】:

    猜你喜欢
    • 2018-07-29
    • 2018-12-16
    • 2017-08-15
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    相关资源
    最近更新 更多