Skip Navigation Links.
 
 

Planned exceptions considered harmful, or try the Try-pattern

by svante@axantum.com 2007-03-06 15:19

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.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

C# | Programming

Related posts

Comments are closed

Programming it real

Name of author

When I'm not riding my bike, I keep fairly busy trying to make a living as a self-employed programmer.

E-mail me Send mail

Recent comments