0
我目前正在使用C++編程原則和實踐,我不太明白如何使用錯誤函數,因爲它在書中使用。錯誤函數的問題
的功能是被列入std_lib_facilities
inline void error(const string& s)
{
throw runtime_error(s);
}
頭文件。
這是一個利用它的小程序。
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()',它將最終中止程序。我不確定我會認爲這完全屬於術語「工作」的含義。我想說或許現在可能是開始尋找更好的書的好時機。 – 2014-10-09 02:14:48
我記得,Stroustrup將頭部設計爲頭幾個星期的學習用途,以便在不需要了解後續概念的情況下更容易起步。無論如何,當一個異常未被捕獲時,您的實現可能會打印該消息。 – chris 2014-10-09 02:19:43
如果沒有catch,那麼程序終止。您的編譯器可能會或可能不會決定顯示消息。你可以在main中添加一個catch處理程序。 – 2014-10-09 02:30:56