我正在尝试在异常后进行清理,但我不确定如何处理StreamWriter。
Dim sw As StreamWriter
Try
''// stuff happens
somethingBad1() ''//Sometimes throws an exception
sw = New StreamWriter(File.Open("c:\tmp.txt", FileMode.Create))
''// stuff happens
somethingBad2() ''//Also sometimes throws an exception
sw.Write("Hello World")
sw.Flush() ''//Flush buffer
sw.Close() ''//Close Stream
Catch ex As Exception
sw = Nothing
Finally
sw = Nothing
end try
如果somethingBad1抛出异常,我不需要对sw
做任何事情;但是,如果发生somathignBad2,则sw
已经创建,我需要关闭它。但我如何知道是否已创建sw
?
答案 0 :(得分:10)
''//stuff happens but you don't care because you didn't instantiate
''// StreamWriter yet
somethingBad1() ''//Sometimes throws an exception
Using sw As New StreamWriter("test.dat")
''// stuff happens
somethingBad2() ''//Also sometimes throws an exception
''//as you are in a using statement the sw.Dispose method would be called
''//which would free the file handle properly
sw.Write("Hello World")
End Using
答案 1 :(得分:2)
仅在分配try
变量后(在您的示例中)执行sw
。或者使用using
声明。
但作为一般规则,您应该关闭StreamWriter(如果不将其与using
一起使用),而不是仅为其分配Nothing。此外,应避免捕获所有异常,只处理您知道如何正常处理的异常。
答案 2 :(得分:1)
达林说得对,但只有一个风格指向扩展Pavel Minaev的评论:与VB6不同,在VB.Net中设置sw
对Nothing
的引用没有实际效果。你真的不需要这样做。你可以做的是在你的finally块中有这样的代码:
Finally
''# test
If sw IsNot Nothing Then sw.Dispose()
End
这会照顾所有所需的清理(包括你对catch块的显示)。您甚至不需要在主代码中关闭流。但Using
块通常是处理此问题的更好方法。