在异常期间如何在StreamWriter之后清理?

BIB*_*IBD 3 vb.net visual-studio

我试图在异常后进行清理,但我不确定如何处理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
Run Code Online (Sandbox Code Playgroud)

如果somethingBad1抛出异常,我不需要做任何事情sw; 但是,如果somathignBad2发生,sw已经创建了,我需要关闭它.但我如何知道是否sw已创建?

Dar*_*rov 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
Run Code Online (Sandbox Code Playgroud)