在VB.NET中,异常处理完毕后如何正确清理StreamWriter资源?
- 内容介绍
- 文章标签
- 相关推荐
本文共计247个文字,预计阅读时间需要1分钟。
我在异常后进行清理,但不确定如何处理StreamWriter。尝试如下:
csharpDim sw As StreamWriterTry ' stuff happens somethingBad() // 可能抛出异常Catch ex As Exception ' s sw=New StreamWriter(File.Open(c:\tmp.txt, FileMode.Create))End Try
我试图在异常后进行清理,但我不确定如何处理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
本文共计247个文字,预计阅读时间需要1分钟。
我在异常后进行清理,但不确定如何处理StreamWriter。尝试如下:
csharpDim sw As StreamWriterTry ' stuff happens somethingBad() // 可能抛出异常Catch ex As Exception ' s sw=New StreamWriter(File.Open(c:\tmp.txt, FileMode.Create))End Try
我试图在异常后进行清理,但我不确定如何处理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

