如何处理传递给构造函数的语法有效但逻辑无效的参数

How to handle a syntactically valid but logically invalid argument passed to the constructor?

本文关键字:有效 语法 参数 无效 构造函数 何处理 处理      更新时间:2023-10-16

我需要创建一个具有公共接口的类Expr,如下所示:

class Expr{
    //...
public:
   Expr(const char*);
   int eval();           //Evaluates the expression and gives the result
   void print();
};

在设计中,如果用户输入了一个无效字符串来构造一个Expr对象,如"123++233+23/45",那么最初构造该对象并在对该对象调用eval()时通知错误是否正确。

或者应该在这一点上检查错误本身并抛出异常,尽管这会导致运行时间的严重增加。用户可以假设Object已经创建,并且只会在运行时发现错误。。

在创建类时总是会出现这样的问题,是否有一种相当标准的方法来处理用户的错误????

关于如何做到这一点的唯一标准部分是全面的文档

我更喜欢尽早抛出错误,或者对这种类型的对象使用工厂——需要初始化特定参数的对象。如果使用工厂,则可以返回NULLnullptr或其他任何值。

我不认为构造对象并仅在调用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; 
}