I need to make a class Expr having public interface like this:
class Expr{
//...
public:
Expr(const char*);
int eval(); //Evaluates the expression and gives the result
void print();
};
In the design, if user enters an invalid string to construct an Expr object like “123++233+23/45”, would it be right to construct the Object initially and notify the error when eval() is called on that object.
Or the error should be checked at that point itself and en exception be thrown, though that would lead to serious increase in runtime. And the user may write code furthur with assumption that Object is created and will discover the error at runtime only..
Such problems arise always in creating a class, is there a rather standard way to handle such errors made at user’s part????
The only standard part about how you do this is thorough documentation.
I prefer throwing the errors as early as possible, or using a factory for objects of this type – objects that require specific arguments to be initialized. If you use a factory, you can return a
NULLor anullptror whatever.I don’t see the point in constructing the object and returning an error only when
eval()is called. What’s the point? The object is invalid anyway, why wait until you use it?Have you profiled this? Don’t not use exceptions because you assume increase in runtime.