我试图在异常后进行清理,但我不确定如何处理StreamWriter. Dim sw As StreamWriterTry ''// stuff happens somethingBad1() ''//Sometimes throws an exception sw = New StreamWriter(File.Open("c:\tmp.txt", FileMode.Create)) ''// s
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?
''//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
