error("some string") 只显示错误,不显示错误+字符串
error("some string") only shows error, not error + string
我正在通过 Stroustrup 的 PP&P Using C++ 学习 C++,我已经到了第五章,其中说:"In fact, in std_lib_fa cilities.h we supply an error() function that by default terminates the program with a system error message plus the string we passed as an argument to 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
函数error(const std::string&)
抛出异常。异常要么在某处被捕获,要么终止程序。在您的情况下, std::runtime_error
抛出 error("...")
不会被捕获。因此,程序简单地终止(一旦发生这种情况就不需要打印任何东西,尽管大多数操作系统会打印一条类似于“调用 std::terminate 后程序退出”的消息)。
您应该做的(如果您实际上不想抛出可能在更高级别捕获的不同异常)只是打印错误:
[...]
catch ( Neq_sqrt )
{
std::cerr << "Sqrt of negative value is not defined!\n";
}
我正在通过 Stroustrup 的 PP&P Using C++ 学习 C++,我已经到了第五章,其中说:"In fact, in std_lib_fa cilities.h we supply an error() function that by default terminates the program with a system error message plus the string we passed as an argument to 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
函数error(const std::string&)
抛出异常。异常要么在某处被捕获,要么终止程序。在您的情况下, std::runtime_error
抛出 error("...")
不会被捕获。因此,程序简单地终止(一旦发生这种情况就不需要打印任何东西,尽管大多数操作系统会打印一条类似于“调用 std::terminate 后程序退出”的消息)。
您应该做的(如果您实际上不想抛出可能在更高级别捕获的不同异常)只是打印错误:
[...]
catch ( Neq_sqrt )
{
std::cerr << "Sqrt of negative value is not defined!\n";
}