Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataReader within try block causing potential null reference error

There is probably is simple fix for this but I currently have code similar to

dim dr as dbDataReader

try
      dr = connection.getDataReader(sql_str)
Catch ex as sqlClientException
     log.error(ex)
finally 

  if not IsNothing(dr) then
    dr.close
  end if
end try

However Visual Studio still warns me that the

if not IsNothing(dr) then
        dr.close
      end if

Can cause a NullReferenceException. What is the best way to mitigate this? I can't move the declaration into the try block.

like image 248
Dean Avatar asked Jan 21 '26 02:01

Dean


1 Answers

Explicitly initialize the dr declaration to Nothing as such:

Dim dr As DbDataReader = Nothing

And the warning will disappear.

like image 143
Jason Stangroome Avatar answered Jan 22 '26 15:01

Jason Stangroome



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!