Friday, July 18, 2008

Don't catch NullReferenceException

Consider the function:

private string GetObjectValue(object param)
{
                try
                {
                    return param.value.ToString();
                }
                catch (NullReferenceException)
                {
                    return "";
                }}

It would be much better to do this:


private string GetObjectValue(object param)
{
                if (param != null)
                {
                    return param.ToString();
                }
                else
                {
                    return "";
                }}

Exceptions are expensive. 
Handling the error adds an average of 16 ticks to the execution in my testing. This will add up.

5 comments:

  1. I know your post is old, but I have a question related to it.
    What if... For example we had 40 different parameters which we wanted to turn into string (like you did), wouldn't it make sense to put all these into a try/catch instead of using one HUGE if or 40 different ifs?

    But thanks for the tip! I think I might do some teting today :P

    ReplyDelete
  2. @Fabian

    Having 40 parameters is a very big code smell. If you really have this many to work with there are probably bigger things you need to concern yourself with than using exceptions to handle null values.

    If you needed to combine this many values I'd approach it like any other large problem. Break it down in to smaller issues and then combine them.
    If you have this many parameters/variables they're presumably part of multiple objects. I'd look to combine the variables from each of the separate objects first.

    Your approach to combining this many variables should also be based on how you'd handle one of them being null. Should that mean you fall back to an exception value? Or do you handle nulls on a per parameter basis?

    ReplyDelete
  3. Anonymous4:30 pm

    This comment has been removed by a blog administrator.

    ReplyDelete