抛出异常场景中的 StreamReader 作用域
在下面的子例程中,当抛出异常时,StreamReader
是否会正确关闭?或者我自己必须做些什么来确保这一点?
Sub mySub()
Dim sr As StreamReader = File.OpenText("someFilename")
Dim line As String = sr.ReadLine()
While Not (line Is Nothing)
' Some logic here
If someCondition Then
Throw New Exception("someExplanation")
End If
line = sr.ReadLine()
End While
End Sub
In the following subroutine, will the StreamReader
be closed properly when the exception is thrown? Or do I have do something myself to ensure this?
Sub mySub()
Dim sr As StreamReader = File.OpenText("someFilename")
Dim line As String = sr.ReadLine()
While Not (line Is Nothing)
' Some logic here
If someCondition Then
Throw New Exception("someExplanation")
End If
line = sr.ReadLine()
End While
End Sub
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该将 StreamReader 变量包装在 using 语句中。
You should wrap the StreamReader variable in a using statement.
在进程终止之前,流不会关闭。即使它确实存在,你也应该关闭它。最好的方法是使用前面提到的“使用”方法。但它不会像写入时那样导致数据丢失。在其他翻译中,您应该关闭 Stream,但这不是批评家。
Stream won't be closed until the process is terminated. Even it does you should close it. Best way is to use "using" method as it mentioned before. But it doesn't cause data loss unlike while writing it does. In other translation, you should close the Stream, but it's not critic.