当前位置 : 主页 > 编程语言 > c语言 >

vb.net – 在异常期间如何在StreamWriter之后清理?

来源:互联网 收集:自由互联 发布时间:2021-06-24
我试图在异常后进行清理,但我不确定如何处理StreamWriter. Dim sw As StreamWriterTry ''// stuff happens somethingBad1() ''//Sometimes throws an exception sw = New StreamWriter(File.Open("c:\tmp.txt", FileMode.Create)) ''// s
我试图在异常后进行清理,但我不确定如何处理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?

''//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
网友评论