.netnullnullreferenceexception

Testing for NullReferenceException (Not Testing for Nothing)


I have a class someone else wrote for which I don't have the source code. It has a property UM that is backed by _UM, a string. In some circumstances _UM is Nothing. I would expect that UM would be Nothing too, but when I inspect (using Quick Watch) the property it shows as a NullReferenceException. When I try testing for Nothing I get a NullReferenceException thrown in my main code. How can I catch this condition so I can handle it properly?

If Foo.UM Is Nothing Then
    DoSomething()
End If

...throws a NullReferenceException.


Solution

  • The property might do more than just return the _UM field. Probably uses it somehow and does not take into account that it might be null. You could do something like this to handle it:

    Dim obj = Nothing
    Try
        obj = Foo.UM
    Catch ex As NullReferenceException
    End Try
    If obj Is Nothing Then
        DoSomething()
    End If