My favourite confusing exception

Spending a lot of time developing websites with Sitecore means I’ve reported my fair share of bugs to support. One particular issue that I came across in 6.6 a while back stands out as my “favourite” issue I’ve reported – just because the error stops a lot of developers in their tracks thinking “how on earth can this happen?”. If you wrote this code, would you think it could crash?

private void doSomething(ShortID identifier)
{
    if(identifier == null)
    {
        // handle the bad paramater
    }

    // do things
}

Well it can crash. And to a less experienced developer it can be a very confusing error:

Null Reference Exception

How can a comparison with null throw a Null Reference exception?

Well the answer is Operator Overloads. You can write a method to change the behaviour of operators like == or != for specific types and if you write it badly it can fail at runtime.

If you dig into the code for Sitecore with your preferred decompiling tool, and look at the ShortID class you’ll find this:

ShortID Overload

When you compare two ShortID values with the == operator the method above gets run. And as you can see it tries to make use of a properties of the objects being passed in without checking them for null. So if any of them are null, you get a Null Reference exception. You’ll also see the same behaviour if you try to compare a ShortID with an ID and the ShortID is null.

This isn’t correct behaviour, and it’s been reported to Sitecore as a bug – so hopefully it’ll get fixed in a future release. But in the meantime, if you see this issue, don’t get confused – just use the ShortID.Equals() method to check for nulls instead:

private void doSomething(ShortID identifier)
{
    if(ShortID.Equals(identifier, null))
    {
        throw new Exception("");
    }

    // do things
}

This code will behave correctly.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s