The Exception object has one purpose and one purpose only – to represent a runtime error, nothing more. Exceptions should never be used for purposes for which they were not intended, or you could end up with this monstrosity.
Take a close look at the following code. This is supposed to be a helper method that determines whether an integer that is passed to it is even or odd.
Hold on, it gets even better. Below is a usage example.
I’ve seen some pretty heavy exception abuse in my time, but I do believe this one wins the cigar.
In the first listing, you can see that the EvenOrOdd method uses an exception as a return type. While this is acceptable in helper methods that create and initialize real exceptions for use elsewhere in your code, that’s definitely not the case here.
Don’t use an exception as a return type or an out parameter for a method.
In the second listing, the page code that uses the method actually requires the the returned exception to be thrown in order to fulfill its normal function.
Exceptions should only be thrown in response to a runtime error. Exceptions should never be used to direct the normal flow of execution in a program.
The scary thing is that this code actually works! Even so, you wouldn’t be caught dead writing code like this… right?
Care to share your favorite Exception Handling WTF?!? Leave a comment and let us all in on the fun.