2014-01-24 | Filed Under Programming
I have had people tell me things like “You should never throw an exception to return a value in an unusual case, exceptions are only supposed to be used for error conditions.” And I HATE it when people say things like this.
There are a couple of audiences at play when we write code. There is the machine that needs to compile and then execute the code. If the code won’t compile or if it runs slowly, wastes memory, or produces incorrect results then we have absolutely failed. The other audience is future readers of the code — other developers who will need to read and maintain the code or even ourselves who will come back months later and say “Oh my God, what was I thinking!” when we read it.
But communicating with these two audiences (the computer and the reader) is all we are doing — we are not playing a game by some arbitrary set of rules. There are no “software police” who will come along and arrest us if we throw an exception, use a goto, fail to start our service name with a verb, or use a URI for our REST API that is inconsistent with some other part of the ontology. (Actually, there may be software police, but if so it is only because they have chosen to self-appoint themselves to that role.) Doing these things might make the results incorrect (for the computer) or difficult to read (for the developer) and that would be bad, but only because it was incorrect or difficult-to-understand, not because it broke some arbitrary rule.
So I would much rather hear someone say one of these things to me:
- “Don’t throw an exception to return a value in this case because creating exceptions is slow, the situation occurs somewhat frequently, and it will reduce the performance of this function which is used in a tight loop and is therefore performance critical.”
- “Don’t throw an exception to return a value in this case because there is error-handling code that will log the exception as an error before it is caught by the handler, thus producing spurious error reports.”
- “Don’t throw an exception to return a value in this case because it will hide the fact that the function actually returns a value and that will be confusing to someone not familiar with it.”
- “Don’t throw an exception to return a value because the other code in this module never does that and it will be inconsistent and therefore difficult for readers of the code.
In other words: It’s great that you’re telling me a different (or better) way to write some code, but don’t tell me to do it because that’s “the right way” (appeal to authority). Instead, tie it back to an actual benefit like correctness or readability.