I found some code on the internet as below (slightly modified).
It simply requests the content of a webpage.
Private Sub readWebpage(ByVal url As String)
Dim Str As System.IO.Stream
Dim srRead As System.IO.StreamReader
Try
' make a Web request
Dim req As System.Net.WebRequest = System.Net.WebRequest.Create(url)
Dim resp As System.Net.WebResponse = req.GetResponse
Str = resp.GetResponseStream
srRead = New System.IO.StreamReader(Str)
' read all the text
textContent.text = srRead.ReadToEnd
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Unable to download content from: " & url)
Finally
srRead.Close()
Str.Close()
End Try
End Sub
However I get two warnings:
Warning 1 Variable 'srRead' is used before it has been assigned a value. A null reference exception could result at runtime.
Warning 2 Variable 'Str' is used before it has been assigned a value. A null reference exception could result at runtime.
I know I can simply forget about the Finally and add the code to the try block.
Will that be the way to go or can I prevent the warnings using a different approach?
Thanks in advance for enlightening me! 🙂
The warning is because if there’s an error on GetResponseStream then your srRead will be null resulting in a Null Exception.
One way to handle this is use Using which will automatically dispose of these objects
You could also go the way Dr. Evil suggests setting the object to Nothing instead of the Using keyword then you’ll want this in your finally