10 August, 2011

Exception Usage Considerations

It seems that I always have the following conversation with different developers.

Them: This method shouldn't throw an exception, it should return an error code.
Me: OK. Why?
Them: Because... umm... exceptions are a terrible means to communicate errors. I want to see a status flag and an error message.

I kinda get the point, but in frameworks such as .NET and Java, it really doesn't make sense to use anything but exceptions.

First, if you use error codes or anything of the sort, you now have the worst of both worlds: the runtime and class library code will throw exceptions and your code will return error codes. Now you have to deal with both.

Second, when returning error codes and messages you have to make assumptions about how application developers will use your code. It's impossible for you to determine under what conditions your code will be used and what assumption the application developer will make about it. It's best to just be consistent and throw an exception when you're not able to complete the work you "contracted" to do through your method signature.

In the interest of completeness: there's perhaps one case in which you should return a flag instead of throwing an exception. When you have a method that gets called frequently and it also has a high failure rate, you'll likely experience a performance hit (from throwing/handling so many exceptions) that won't be tolerable.

Microsoft, for example, had the above problem with the Int32.Parse method. To address the issue MS introduced TryParse. This new method returns a flag telling you whether worked and returns the value of the parse in and output parameter called result.

It's important to note, however, that the boolean flag returned only indicates one type of failure: the method's inability to parse the string into an integer. The method still throws an ArgumentException if the argument is not valid.

So there you have it: always use exceptions. And if you're not going to listen to me, use error flags to indicate just one type of error.