Pretty new to C#, and I’d like to know how should I be using exceptions? I mean, not a mechanics level, but at a good practice level.
I’ll use for example my calculator which tokenizes and the converts to RPN and solves problems given in RPN.
During the tokenizing step there’s various invalid inputs, say “7.7.8” or “^&##”, should I have separate exceptions for unknown symbols and invalid numbers? Is it wrong to say have a single exception and then a method in it containing the kind of error, to be given to the user?
I’ve really not been able to find much material on this kind of thing, so I thought I’d ask people with more experience than me.
—–Edit:
Thanks everyone for your awesome responses, I learned a ton today 🙂 about my question, and even more for that matter.
Think about your lexer from the perspective of preconditions and postconditions. Here are two ways to design a lexer :
A lexer is a device which takes in a well-formed input string and outputs a lexical analysis. The input string is required to be well-formed; if it is not then the lexical analyzer fails with an exception.
A lexer is a device which takes an input string and produces a lexical analysis. Lexical analysis includes identification of and analysis of error conditions.
Do you know that the string you’re going to pass in is correct, and you want an exception in the exceptional circumstance that it is incorrect? Or do you not know that the string is correct, and you wish the lexer to determine that?
In the former case, throw an exception. In the latter case, make the error analysis part of the output of the lexer.
Basically what I’m saying is do not produce vexing exceptions. Vexing exceptions are extremely irritating. If the caller of your code is calling it to determine whether the string is correct then they don’t want that information in the form of an exception, they want it in the form of a data object that represents the error analysis. If the purpose of the code is to produce an error analysis then produce such an analysis as the normal operation of the method. Do not embed the analysis in an exception and make someone trap the exception in order to get it.