有错误功能的麻烦

时间:2014-10-09 02:12:19

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

我目前正在使用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");
}

我的问题是,如果在抛出错误时没有抓住错误以便显示您的消息,那么此错误函数如何工作?

1 个答案:

答案 0 :(得分:0)

确保打印出错误消息,您需要自己执行此操作,而不是依赖于实施质量。

像,

#include <iostream>      // std::cout, std::cerr
#include <stdexcept>     // std::runtime_error
#include <stdlib.h>      // EXIT_FAILURE, EXIT_SUCCESS
#include <string>        // std::string
using namespace std;

auto fail( string const& s ) -> bool { throw runtime_error( s ); }

void cpp_main()
{
    // What you would otherwise put directly in `main`, e.g.
    cout << "x? ";
    double x;
    cin >> x
        || fail( "Uh oh, that was not a valid value for x." );
}

auto main() -> int
{
    try
    {
        cpp_main();  return EXIT_SUCCESS;
    }
    catch( exception const& x )
    {
        cerr << "!" << x.what() << endl;
    }
    return EXIT_FAILURE;
}

免责声明:编码器未触及的代码&#39;手。


提示:您可以使用免费的AStyle格式化程序来修复代码的格式。