Question

I basically read across the entire internet that exceptions are bad, slow and should be avoided whenever possible. This confuses me because I thought I have a "valid" case to use exceptions.

Consider an input parser which transforms a string into an expression tree, that a calculator can evaluate. For me this seems perfectly suited for exceptions, see the following Pseudo-Code

try:
    expression_tree = input_parser.parse(user_input);

    print "Result: " , calculator.evaluate(expression_tree);

catch division_by_zero e:
    print "Error: Division by zero near: " , e.code_window();

catch matrix_dimension e:
    print "Error: Matrix dimension don't match near: ", e.code_window();

catch ...

Since I do not plan to fix the error, just catch it and then ask for a new input, the speed factor should be of no concern. Furthermore this makes the code well readable and easy to handle, as I don't need error codes or manual jumps / premature exits from functions. But as I've stated, the overall attitude towards exceptions makes me doubt myself.

Was it helpful?

Solution

There are no shortage of complaints about throwing and catching both within the same method.  These are considered a form of goto, considered harmful.

Throwing an exception when we don't want to proceed — e.g. with parsing — is different and is reasonable usage of exceptions.


However, in your code you might abstract the exceptions a bit by making one root exception, say, an abstract parse_error class with a method to print itself.  Your parser will then have a bit more flexibility in generating error messages, and your outer handler won't have to check for all the specific exceptions.  (Of course, division by zero shouldn't happen in the parser — if it does then the parser is really more than that, like an interpreter, or possibly an optimizer.)

OTHER TIPS

Exceptions should be used for exceptional cases. A parse error is not exceptional; an input that can be parsed correctly is probably more exceptional: -(

Licensed under: CC-BY-SA with attribution
scroll top