How to clear after StreamWriter during an exception?

I am trying to clear after an exception, and I'm not sure how to handle 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 with sw; however, if somathignBad2 occurs, it is swalready created, and I need to close it. But how do you know if it was created sw?

+3
source share
3 answers
''//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
+9
source

Perform tryonly after assigning a variable sw(in your example). Or use an operator using.

, , StreamWriter ( using), . , , , .

+2

, , : VB6, VB.Net sw Nothing . . , finally:

Finally
    ''# test
    If sw IsNot Nothing Then sw.Dispose()
End

And this will take care of all the necessary cleanups (including what you show in the catch block). You would not even need to close the stream in your main code. But Usingblocks are usually the best way to handle this.

+1
source

Source: https://habr.com/ru/post/1716820/


All Articles