There have been a number of similar questions here, but none explains what is happening in my case; so here goes.
I have the following (simplified) piece of code:
' row is a System.Data.DataRow
' _typeProperties is a Dictionary(Of String, PropertyInfo)
Dim data As New Dictionary(Of String, Object)
Dim elem As KeyValuePair(Of String, PropertyInfo)
Dim value As Object = Nothing
Try
For Each elem In _typeProperties
value = row.Item(elem.Key)
data.Add(elem.Key, value) ' NullReferenceException here
Next
Catch ex As Exception When MyExceptionFilter(ex, data, elem, value)
End Try
Sometimes I get a NullReferenceException on the indicated line. This exception is exceedingly rare and I cannot reproduce it at will. However, I can modify my application, send it out to a customer and sure enough, after some days it will reproduce on its own.
The call stack is not very helpful:
StackTrace:
XXX.RowToType(DataRow row) in C:\XXX.vb:line 645.
Moreover, as you can see I included an exception filter in the Catch block. In there I write a minidump (with the call stack of the exception intact). Here is the relevant portion of the call stack revealed by the minidump:
...
App.exe!MyExceptionFilter( ex, data, elem, value) Line 627
App.exe!RowToType( row) Line 647 + 0x1f bytes
[External Code]
App.exe!RowToType(System.Data.DataRow row) Line 645 + 0x112 bytes
App.exe!SomeClass.get_Item(Integer index) Line 1141 + 0xe bytes
user32.dll!_InternalCallWinProc@20() + 0x23 bytes
user32.dll!_UserCallWinProcCheckWow@32() + 0x693 bytes
...
The exception happens somewhere in the [External Code] block; then the filter of the Catch block gets executed (line 2 & line 1).
At the moment of the exception, these are the values for the three involved variables:
data: Not Nothing;
elem: Not Nothing;
elem.Value: Not Nothing (Int32 ID)
elem.Key: Not Nothing
value: Nothing
So there appears to be absolutely no reason for data.Add to throw a NullReferenceException.
As some people suggested in other questions, there might be some threading issue. However, the dictionary to which I am writing can by definition only be visible to one thread. (And to be sure, I also checked the minidump to make sure that no thread is executing the same code.)
I might just silently ignore this exception, but I'd rather figure this out.
_typeProperties
? – JeffRSon 17 hours ago