bhu*_*hni 5 c++ error-handling class
我需要创建一个具有这样的公共接口的类Expr:
class Expr{
//...
public:
Expr(const char*);
int eval(); //Evaluates the expression and gives the result
void print();
};
Run Code Online (Sandbox Code Playgroud)
在设计中,如果用户输入无效字符串来构造Expr对象,如"123 ++ 233 + 23/45",那么最初构造Object并在对该对象调用eval()时通知错误是否正确.
或者应该在该点检查错误本身并抛出异常,但这会导致运行时严重增加.并且用户可以编写代码,并假设创建了Object,并且仅在运行时发现错误.
这样的问题总是在创建一个类时出现,是否有一种相当标准的方法来处理用户的这些错误?
关于如何执行此操作的唯一标准部分是完整的文档.
我更喜欢尽早抛出错误,或者使用工厂来处理这种类型的对象 - 需要初始化特定参数的对象.如果您使用工厂,您可以退回一个NULL或一个nullptr或其他.
我没有看到构造对象的意义,只有在eval()调用时才返回错误.重点是什么?无论如何,对象无效,为什么要等到你使用它?
并抛出异常,但这会导致运行时间的严重增加.
你有没有想过这个?不要因为假设运行时间增加而使用异常.
class illogical_expression_exception : public virtual exception {};
class Expr{
//...
int result; // store evaluated result.
public:
explicit Expr(const char*);
int getResult(); // Evaluate & Parse in the Constructor.
void print();
};
/* in constructor */
if ( ! checkExpression(expr) ) throw illogical_expression_exception();
/* in main() */
try{ Expr my_expr("2+2*2"); }
catch(const illogical_expression_exception& e){
cout << "Illogical Expression." << endl;
}
Run Code Online (Sandbox Code Playgroud)