PeeHaa
PeeHaa

Reputation: 72672

prevent warnings on variables which aren't assigned a value in a Try

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! :)

Upvotes: 1

Views: 2955

Answers (2)

Conrad Frix
Conrad Frix

Reputation: 52645

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

 Private Sub readWebpage(ByVal url As String)
        Try
            ' make a Web request
            Dim req As System.Net.WebRequest = System.Net.WebRequest.Create(url)
            Dim resp As System.Net.WebResponse = req.GetResponse
            Using Str As System.IO.Stream = resp.GetResponseStream
                Using srRead As System.IO.StreamReader = New System.IO.StreamReader(Str)
                    textContent = srRead.ReadToEnd
                End Using
            End Using


    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, "Unable to download content from: " & url)

    End Try
  End Sub

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

Finally 
        If Str Is Not Nothing Then
            Str.Close
        End If
        If srRead Is Not Nothing Then
            srRead.Close
        End If
End Try

Upvotes: 3

dr. evil
dr. evil

Reputation: 27265

You can simply set them Nothing by default, this way you'll inform the compiler you know what you are doing :)

Dim Str As System.IO.Stream = Nothing

Upvotes: 10

Related Questions