防止在 Try 中未分配值的变量出现警告
我在互联网上找到了一些代码如下(稍作修改)。
它只是请求网页的内容。
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 块中。
这是可行的方法还是我可以使用不同的方法来防止警告?
预先感谢您启发我! :)
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! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下,您可以简单地将它们设置为 Nothing,这样您就可以通知编译器您知道自己在做什么:)
You can simply set them Nothing by default, this way you'll inform the compiler you know what you are doing :)
该警告是因为如果 GetResponseStream 出现错误,那么您的 srRead 将为 null,从而导致 Null 异常。
处理这个问题的一种方法是使用Using,它会自动处理这些对象
你也可以按照Dr. Evil建议的方式将对象设置为Nothing而不是Using关键字,然后你会希望在你的finally中使用它
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