Catch NullReferenceException or test for Nothing first?

hawbsl picture hawbsl · Nov 12, 2010 · Viewed 18.2k times · Source

We have a property whose job is to look up a description. If the lookup fails it should show an empty string.

So we can code the property like this:

If foo.bar Is Not Nothing Then
  Return foo.bar.Description
Else
  Return String.Empty
End If

But that involves executing foo.bar twice, and if doing so is expensive, it's probably better like this:

Dim b As bar = foo.bar
If b IsNot Nothing Then
  Return b.Description
Else
  Return String.Empty
End If

But really all we want to do is treat any kind of error as an empty description. So in some ways this is simpler:

Try
  Return foo.bar.Description
Catch e As NullReferenceException
  Return String.Empty
End Try

But are there any problems (performance, purity, other?) with just catching and ignoring the error?

You sometimes read it's expensive to throw an exception but I am not sure whether the author means it's expensive to build in exceptions using the Throw keyword (which I am not doing) or whether he means it's expensive to allow exceptions to occur (as I would be doing).

Answer

Fredrik Mörk picture Fredrik Mörk · Nov 12, 2010

If would definitely test for Nothing instead of relying on exceptions here. You code indicates that the scenario where foo.bar is Nothing is an expected scenario, and not an exceptional one. That sort of gives the answer.

Throwing an exception is a relatively expensive operation (from a performance perspective). This is the case regardless of wheter you are throwing it in your code, or if it is thrown in library code; it's exactly the same operation. However, I would not keep from throwing exceptions for performance reasons unless I had a real, measured, critical business case.

In my opinion this is mostly a matter of showing intent; by testing for Nothing and acting gracefully on that, your code expresses the fact that this is not a strange thing to happen.

If you are worried about the performance in executing foo.bar twice, the first thing to do is to find out if that is really the case. If so, there are probably ways of solving that (your code sample already contains a suggestion).