【发布时间】:2014-10-09 02:12:19
【问题描述】:
我目前正在使用 C++ 进行编程原理和实践,但我不太了解如何使用书中使用的错误函数。
功能是
inline void error(const string& s)
{
throw runtime_error(s);
}
包含在 std_lib_facilities 头文件中。
这是一个利用它的小程序。
int main()
{
cout << "Please enter expression (we can handle +, –, *, and /)\n";
cout << "add an x to end expression (e.g., 1+2*3x): ";
int lval = 0;
int rval;
cin>>lval; // read leftmost operand
if (!cin) error("no first operand");
for (char op; cin>>op; ) { // read operator and right-hand operand
// repeatedly
if (op!='x') cin>>rval;
if (!cin) error("no second operand");
switch(op)
{
case '+':
lval += rval; // add: lval = lval + rval
break;
case '–':
lval –= rval; // subtract: lval = lval – rval
break;
case '*':
lval *= rval; // multiply: lval = lval * rval
break;
case '/':
lval /= rval; // divide: lval = lval / rval
break;
default: // not another operator: print result
cout << "Result: " << lval << '\n';
keep_window_open();
return 0;
}
}
error("bad expression");
}
我的问题是,如果在抛出错误时没有 catch 来捕获错误,那么这个错误函数应该如何工作,以便显示您的消息。
【问题讨论】:
-
在您显示的代码中,如果调用
error(),它将最终在当时和那里中止程序。我不确定我是否会认为这完全属于“工作”一词的含义。我想说也许现在是开始寻找更好的书的好时机。 -
我记得,Stroustrup 将标题设计为在最初几周的学习中使用的东西,这样开始时会更容易,而无需了解以后的概念。无论如何,当一个异常未被捕获时,您的实现可能会打印该消息。
-
如果没有
catch,则程序终止。您的编译器可能会或可能不会决定显示该消息。您可以在 main 周围添加一个 catch 处理程序。 -
“在 std_lib_facilities.h 中,我们提供了一个 error() 函数,默认情况下该函数会使用系统错误消息以及我们作为参数传递给 error() 的字符串来终止程序。”这只是有点令人困惑。我知道如果您添加 catch 语句,它将按预期工作,只是想问我是否遗漏了什么。
标签: c++ error-handling runtime-error