The Greatest Exception Handling WTF?!? of All Time
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.
public static class NumberHelpers
{
public static ApplicationException EvenOrOdd(int integer)
{
if (integer % 2 == 0)
{
return new ApplicationException(“The integer is even.”);
}
else
{
return new ApplicationException(“The integer is odd.”);
}
}
}
Hold on, it gets even better. Below is a usage example.
protected void btnTest_Click(object sender, EventArgs e)
{
try
{
throw NumberHelpers.EvenOrOdd(Convert.ToInt32(txtIntToTest.Text));
}
catch (ApplicationException ex)
{
litResult.Text = ex.Message;
}
}
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.
Subscribe to this blog for more cool content like this!
You've been kicked (a good thing) - Trackback from DotNetKicks.com
Pingback from DevLanfear - .NET
Pingback from links for 2009-05-28 | Xelluloid
Pingback from links for 2009-05-28 | Xelluloid
Thank you for submitting this cool story - Trackback from DotNetShoutout
Pingback from MsHelp » Week 22: Things I need to check out
Pingback from Exceptions are for Exceptions
Pick of the week: The Holy Grail is NOT Automation General .NET 4 Cancellation Framework : A post by the Parallel FX team about how you’ll be able to build cancellation-aware applications in .NET 4.0. Why Defer Loading in Entity Framework Isn’t Going
Pingback from The Rules of the Game « AJ’s blog