防止在Try中未赋值的变量发出警告

时间:2010-12-22 21:32:08

标签: .net vb.net try-catch try-catch-finally

我在互联网上找到了一些代码,如下所示(略有修改)。

它只是请求网页的内容。

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

但是我得到两个警告:

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.

我知道我可以忘记Finally并将代码添加到try块中。

这是可行的方法,还是可以使用其他方法阻止警告?

提前感谢您的启发! :)

2 个答案:

答案 0 :(得分:10)

默认情况下你可以简单地设置它们,这样你就会告诉编译器你知道你在做什么:)

Dim Str As System.IO.Stream = Nothing

答案 1 :(得分:3)

警告是因为如果GetResponseStream上有错误,那么你的srRead将为null,从而导致Null异常。

处理此问题的一种方法是使用“自动处理这些对象”

 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

您也可以采用Dr. Evil建议将对象设置为Nothing而不是Using关键字的方式,然后您将在最终

中想要这个
Finally 
        If Str Is Not Nothing Then
            Str.Close
        End If
        If srRead Is Not Nothing Then
            srRead.Close
        End If
End Try
相关问题