Tuesday, March 6, 2007

Planned exceptions considered harmful, or try the Try-pattern

A really common misuse of exceptions in code is to validate input. A typical code pattern may look something like this:

private int GetIntValue(string s)
{
int i;
try
{
i = int.Parse(s);
}
catch (Exception)
{
i = -1;
}
return i;
}

This is bad. Very bad. The exception is not an exception, it's an expected outcome of validating the input. That is not the way of doing this. Enter the TryXXX pattern, implemented in various parts of the .NET Framework 2.0 and later, and hopefully soon in your code! It should look like this:

private int GetIntValue2(string s)
{
int i;
if (int.TryParse(s, out i))
{
return i;
}
return -1;
}

The TryXXX pattern is a very nice way to handle the situation that you're expecting, and want to handle, bad input. In your own implementation, you should not just wrap a try-catch block with the TryXXX pattern, you should ensure that your data is valid without generating an exception in the first place.

If other parts of the code is not expecting any invalid input, and the right thing to do indeed is to throw an exception, then it's the TryXXX that should be wrapped, and if it fails throw the exception.

No comments:

Post a Comment