抛出异常场景中的 StreamReader 作用域

发布于 2024-11-30 23:48:44 字数 403 浏览 0 评论 0原文

在下面的子例程中,当抛出异常时,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

平安喜乐 2024-12-07 23:48:44

您应该将 StreamReader 变量包装在 using 语句中。

Using sr as StreamReader = File.OpenText("someFilename")
...
End Using

You should wrap the StreamReader variable in a using statement.

Using sr as StreamReader = File.OpenText("someFilename")
...
End Using
¢蛋碎的人ぎ生 2024-12-07 23:48:44

在进程终止之前,流不会关闭。即使它确实存在,你也应该关闭它。最好的方法是使用前面提到的“使用”方法。但它不会像写入时那样导致数据丢失。在其他翻译中,您应该关闭 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文