how do I clean up after a StreamWriter during an exception?
vb.net, visual-studio
Solution
''//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
Problem
I'm trying to clean-up after an exception, and I'm not sure how to handle a 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 ``` If somethingBad1 throws an exception, I don't need to do anything to `sw`; however, if somathignBad2 happens, `sw` has already been created and I need to close it. But How do I know if `sw` has been created or not?