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).