Malcolm McCaffery

Hi there,

I'm fairly new to VB.NET and love it but I'm not sure how to prevent a null exception from occuring. I can use the Try ... Catch to prevent the program crashing but I would prefer not to use this method. Is there a way to test for this without throwing exception I need to return a blank value for objUserInfo.Properties.Item("mail").Value for example if nothing is found.

I'm building a string from data gathered in active directory to output to a CSV file. It seems if a value is blank then an exception is thrown.

The relevant section of code is:

Dim objUserInfo As DirectoryEntry

Try

objUserInfo = GetUserInfo(objSubFolder.Name) '

' Exception occurs on the following line

s = s & "," & objUserInfo.Properties.Item("givenName").Value & " " & _

objUserInfo.Properties.Item("sn").Value & "," & _

objUserInfo.Properties.Item("mail").Value

Catch ex As Exception

' I don't want to do it this way

s = s & ",none,none"

End Try

Public Function GetUserInfo(ByVal LoginName As String) As DirectoryEntry

Dim objRootEntry As DirectoryEntry = New DirectoryEntry()

Dim objADSearcher As DirectorySearcher = New DirectorySearcher(objRootEntry)

objADSearcher.Filter = "(&(objectCategory=person)(sAMAccountName=" & LoginName & "))"

Dim objResult As SearchResult = objADSearcher.FindOne()

If (Not objResult Is Nothing) Then

GetUserInfo = objResult.GetDirectoryEntry()

Else

GetUserInfo = Nothing

End If

End Function



Re: Visual Basic Language prevent null exception from occurring

Spidermans_DarkSide

Hi,

Have you declared s AS a String or something

Regards,

S_DS






Re: Visual Basic Language prevent null exception from occurring

Malcolm McCaffery

Yes s is declared as a string.



Re: Visual Basic Language prevent null exception from occurring

Spidermans_DarkSide

Hi,

If objUserInfo.Properties.Item("mail").Value = Nothing And _

objUserInfo.Properties.Item("sn").Value = Nothing And _

objUserInfo.Properties.Item("givenName").Value = Nothing Then

s = s & " , , "

Else

s = s & "," & objUserInfo.Properties.Item("givenName").Value & " " & _

objUserInfo.Properties.Item("sn").Value & "," & _

objUserInfo.Properties.Item("mail").Value

EndIf

The above would sort it out. :-)

Regards,

S_DS






Re: Visual Basic Language prevent null exception from occurring

DMan1

If Not String.IsNullOrEmpty(objUserInfo.Properties.Item("mail").Value ) Then

End If






Re: Visual Basic Language prevent null exception from occurring

Kea

Yes, you should always check that you don't pass a null reference to any method. Exceptions affect performance and should not be relied upon if you can verify the conditions before the call.




Re: Visual Basic Language prevent null exception from occurring

Frank Carr

Another way to deal with this is to initialize your string variable when you declare it, for example:

Dim MyValue As String = ""

This will cause it to act more like classic VB and earlier Basics that would do this for you behind the scenes.






Re: Visual Basic Language prevent null exception from occurring

Kea

Yes, but string.IsNullOrEmpty() is just genius and very expressive.




Re: Visual Basic Language prevent null exception from occurring

Spidermans_DarkSide

 DMan1 wrote:

If Not String.IsNullOrEmpty(objUserInfo.Properties.Item("mail").Value ) Then

End If

Hi,

 I understand an empty string such as "" but is NULL not ascii character zero

See http://www.asciitable.com

 I get that NOTHING is a reference to no declared object unlike

Dim myInt As Integer = 0

Dim myString As String=""

 

Regards,

S_DS

 






Re: Visual Basic Language prevent null exception from occurring

SJWhiteley

Note that the above does not prevent a null exception error (only if the value is a null or empty):

If Not String.IsNullOrEmpty(objUserInfo.Properties.Item("mail").Value ) Then

End If

Since there are 3 other objects being referenced that may be nothing - thus a null reference exception could still be thrown. Typically, as long as the types are cast correctly, 2 exceptions are likely, and need to be additionally checked.

1. objUserInfo is nothing - pretty self evident: an Is Nothing check will solve that.

2. The Item doesn't exist - you can't check the Value property of an Item if it doesn't exist... :)

(edit: if my count is correct there are 8 chances for an exception to be thrown in the OP code).






Re: Visual Basic Language prevent null exception from occurring

Spidermans_DarkSide

SJWhiteley wrote:

(edit: if my count is correct there are 8 chances for an exception to be thrown in the OP code).

Hi,

Is there not 9 chances 3 per each item

Regards,

S_DS






Re: Visual Basic Language prevent null exception from occurring

Kea

Just check every reference or string that the call target expects to use, while stilling catching the exceptions. Fuzz the input and when you catch a new NullReferenceException go back and see if there was something your code didn't catch before the call. If you can avoid most exceptions, fine, you don't have to avoid all of them as long as your application catches them and recovers gracefully.




Re: Visual Basic Language prevent null exception from occurring

SJWhiteley

, if they were in isolation then yes. But even so, you missed two (considering only the try block, of course).

Here's a hint: once the 'properties' has thown a Null Reference, then the other two 'Items' will not throw an error - it's already been thrown.

Try counting again... (I just recounted, and I think it's still 8...)

Actually, it's a good exersize - if, as a programmer, you aren't familiar with exceptions, when they can be thrown and why, then there is no chance that you'll write a reliable program. Likewise, catching 'all' exceptions is a bad idea: in this case, only a nullReferenceException should be caught (assuming the Try catch is kept, which it shouldn't).






Re: Visual Basic Language prevent null exception from occurring

DMan1

Just to clarify..The sample given by me is a means to prevent the null exception error...and SJ is correct that each instance/value would have to be checked for Null...not just the single one given in the sample




Re: Visual Basic Language prevent null exception from occurring

Dick Donny

Hi Malcolm

As discussed already, there are a number of points at which a null value exception could theoretically be raised.  You can defensively code around the exception conditions ... perhaps something along these lines (I've assumed your code is running in a for loop)

dim sb as new stringbuilder

'' start loop to get objsubfolder reference

dim objuserinfo as directoryentry = getuserinfo(objsubfolder.name) : if objuserinfo is nothing then continue for

dim properties as propertycollection = objuserinfo.properties : if properties is nothing then continue for

dim a(2) as string

if properties.contains("givenName") then a(0) = properties.item("givenName").value.tostring else a(0) = "none"

if properties.contains("sn") then a(1) = properties.item("sn").value.tostring else a(1) = "none"

if properties.contains("mail") then a(2) = properties.item("mail").value.tostring else a(2) = "none"

sb.appendline(string.format("{0},{1},{2}", a)

'' end loop

return sb.tostring

I personally like to code this way as it is explicit in its intent and simple to follow. 

Note the above could still error if the propertiescollection allows null entries for keyed values (not sure if it does).  If it does, refactor the code a little so the tostring method is not called direct from the read (read it into a holding variable and then use String.IsNullOrEmpty to check it.

I hope you find the contents useful.

Richard