简体   繁体   中英

ignore null reference exception vb.net

I am coding in vb.net. At times the data is empty/null this is due to user's input into the db. i will like to bypass it, however i get no luck.

here is snippet of my code:

If hct.mydbvalue.name IsNot Nothing Then
   dr("mydbvalue") = hct.mydbvalue.name
End If

I still get an error:

System.NullReferenceException: Object reference not set to an instance of an object.

is there a way if it is a null value to not do anything?

Both @FishBasketGordo and @Yuck are correct, you need to check the full object path for nullability:

If (hct IsNot Nothing) AndAlso (hct.mydbvalue IsNot Nothing) AndAlso (hct.mydbvalue.name IsNot Nothing) Then
   dr("mydbvalue") = hct.mydbvalue.name
End If

You won't get a NullReferenceException from data in the database that's null when using ADO.NET; ADO.NET uses DBNull.Value to represent null, so your null reference is coming from somewhere else. In the code above, your exception could occur if any of the following were null:

  • hct
  • hct.mydbvalue
  • dr

from VS14+ you can use

If hct?.mydbvalue?.name IsNot Nothing Then dr("mydbvalue") = hct.mydbvalue.name End If

Make sure that the whole chain is not null. If hct or mydbvalue is null, you'll get the exception.

You should be checking whether hct is Nothing , as well as mydbvalue . If you look at the exception message property, it will tell you which is causing the error.

To me this looks like hct.mydbvalue is null, and therefore you can't call "name" on it.

Private Function NullCheck(ByVal inObject As Object, Optional ByVal defaultValue As Object = "") As Object
    Dim out As Object
    If Not IsDBNull(inObject) Then
        out = inObject ' This returns the value that was passed in when it is not null
    Else
        out = defaultValue ' This ensures that out is something and defaults to ""
    End If
    Return out
End Function

I'm also solving this problem, but in C#.

On my project we've complex object paths like "RootObject.childObject.LitleObject.TinyObject.StringName"

when any of these objects in the path is null, you'll get a null reference when you try something easy like

if(RootObject.childObject.LitleObject.TinyObject.StringName == "a")

I would be okay if it just works as whole rest of the path will be null.

eg. when childObject = null, then I want also RootObject.childObject.LitleObject.TinyObject.StringName to be null, not null reference exception.

However I've found no solution yet, but there is one new operator which can slightly help you in some null tasks.

a = object.object?? defaultValue;

operator?? is something like ISNULL in SQL server. If object on left is null, it returns the object from right.

It also replaces whole function NullCheck posted by Michael above.

Hope this will help a bit.

more info on operators http://msdn.microsoft.com/en-us/library/ms173224(v=vs.80).aspx http://msdn.microsoft.com/en-us/library/6a71f45d(v=vs.80).aspx

you're talking about diferent things.

It doesn't matter if you use ISDBNull(xy), String.IsNullOrEmpty(xy) or (xy=null)

The problem is far sooner than your selected function is called.

when X is null, it cannot have a property Y. so when you call

AnyOfYourPrefferedFunctions(x.y);

the error raises during evaluation of xy (null. doesn't exist), so it stops before the machine actually knows what is the function you want to call.

Probably only way to check this, would be using reflection. But you would need to send string with path and reference to root. so something like:

var v = GetValueThroughReflection(rootObject, "rootObject.path.to.the.last.object");

Then you'll be able to write a function which will go through the object path and find which one is null and handle it accordingly. eg returns null.

But when you'll heavy use that function, it can make your application run slower. as you'll use reflection for such simple task as is getting value out of variable.

Try inserting a IF NOT isdbnull(hct.mydbvalue.name)

The following code checks all values.

If hct IsNot Nothing AndAlso 
   hct.mydbvalue IsNot Nothing AndAlso
   Not String.IsNullOrWhitespace(hct.mydbvalue.name) Then

    dr("mydbvalue") = hct.mydbvalue.name

End If

Note that the last test used String.IsNullOrWhitespace(). I'm assuming name is a string and you don't want to save empty strings.

Update 1

The following code is a simple console application to prove that using IsDbNull() or Micheal's NullCheck() will throw NullReferenceException when hct.mydbvalue is Nothing.

Module Module1

    Sub Main()

        Dim hct = New hct
        Dim dr = New Dictionary(Of String, String)
        Dim errorCount = 0

        Try
            Dim thisCallWillFail = IsDBNull(hct.mydbvalue.name)

        Catch ex As NullReferenceException
            Console.WriteLine(
                "Using IsDBNull() threw NullReferenceException as expected."
            )
            errorCount += 1

        End Try

        Try
            Dim thisCallWillFail = NullCheck(hct.mydbvalue.name)

        Catch ex As NullReferenceException
            Console.WriteLine(
                "Using NullCheck() threw NullReferenceException as expected."
            )
            errorCount += 1

        End Try

        Console.WriteLine("errorCount = 2? {0}", errorCount = 2)

    End Sub

    Private Function NullCheck(ByVal inObject As Object, 
                               Optional ByVal defaultValue As Object = "") As Object

        Dim out As Object

        If Not IsDBNull(inObject) Then

            ' This returns the value that was passed in when it is not null
            out = inObject 

        Else

            ' This ensures that out is something and defaults to ""
            out = defaultValue 

        End If

        Return out

    End Function

End Module

Public Class hct
    Property mydbvalue As mydbvalue
End Class

Public Class mydbvalue
    Property name As String
End Class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM