Parser - Error Handling |
|
The calculator will blow up if you parse an illegal
string and do not object. Fortunately, error-handling is
trivial. Start with parenthesis - use an open parenthesis
counter. Add one with every (, subtract with every ). If you
go negative, you have an unmatched ). If you end positive, you
have an unmatched ( - reverse the process to find which one is
unmatched.
What else should you catch? Well, if you do not allow unary operators, every expression ends up being: operand operator operand so, if the previous token is an operand, the next token is either an operator or a ). If the previous token is an operator, the next token is either an operand or (. To make this work, I usually treat negative numbers as (0-number). Finally, sophisticated error-handling requires careful handling of parenthesis: for example () will not be caught by any of the means above. |