我正在尝试在发生异常后进行清理,但我不确定如何处理 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做任何事情;但是,如果 somatignBad2 发生,则 sw
已经创建,我需要关闭它。但是我如何知道 sw
是否已创建?
最佳答案
''//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
关于vb.net - 在发生异常期间如何在 StreamWriter 之后进行清理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1374787/