Friday, March 10, 2006

There's a reason they are called exceptions

Whenever you read about exceptions, one of the key points is that exceptions should only be thrown in exceptional circumstances. An example might be when a file the application can't survive without doesn't exist. However I've seen on several occassions now exceptions being used where the particular problem could be expected to happen on a fairly regular basis, if not every time the application runs. A common example can be found when trying to convert a string to an int. In .NET 1.1, int doesn't have a TryParse method so a quick and dirty approach to implementing similar functionality might be as shown here
int val = 0;
try
{
  val = int.Parse(stringVal);
}
catch (FormatException)
{
}
This solution can be fine when stringVal will generally be a valid int, but if it's used when stringVal is often not a valid int (when reading the value from a config file that by default doesn't contain any value for instance), it can become annoying. Why's that then I hear you cry? Just turn off breaking into the debugger when an exception is thrown and all is well. Well perhaps but I always want to break into the debugger when an exception is thrown. Why not just break into the debugger for unhandled exceptions? Because my applications have a global exception handler to do logging etc when an unexpected exception is thrown. So turning off breaking into the debugger when an exception is thrown means I never break into the debugger for any exceptions, which is less than ideal. When developers follow this pattern too often, it can actually become increasingly difficult to ever break into the debugger when an exception is thrown. The IDE option can be become impossible to switch on because the developer is thrown back into the IDE so often. When this happens, we've lost a very useful tool and our debugging becomes much more difficult. Having the option always switched on means we are more likely to find those obscure bugs that only happen once in a blue moon. Another point to make is that this kind of exception handling can affect not only the developers working on your project but developers working on something completely different. I've been working on an ASP.NET project that requires me to run another ASP.NET project at the same time. This other project uses a very similar technique as that shown above which constantly throws me back into the debugger when I'm working on my own project! So how to solve the problem? In the case of the code above, there are probably several solutions, although they will all require some work. Checking for an empty string often solves the problem in 90% of cases, whilst doing some kind of check of the characters in the string would cover the other cases. For most other scenarios where an exception will be thrown, there is almost always a different implementation approach that does not require exceptions.

No comments: