views:

43

answers:

3

Consider the code:

On Error Goto ErrorHandler

Using sr As StreamReader = New StreamReader(OpenFile)
    str = sr.ReadToEnd
    sr.Close()
End Using

Exit Sub

ErrorHandler:

If there is an error inside the Using block how do you clean up the sr object?

The sr object is not in scope in ErrHandler so sr.Close() cannot be called. Does the Using block cleanup any resources automatically even if there is an error?

+1  A: 

Yes, the using block will automatically call IDisposable.Dispose (which, for a StreamReader is the same as calling Close) so there's nothing you need to do (that's the whole point of using blocks!)

Dean Harding
@codeka: what if there is an error during the Using block? Will it still call Close()?
Craig Johnston
Yes, that's what the using block's purpose is. Whenever program execution leaves the block, it will call Dispose.
Thorarin
+2  A: 

As codeka says, you don't need to call Close on sr. It'll called automatically, and that includes if there is an error. Using the using statement gives you the same functionality as try ... finally ... end try.

And as you see in the answers to your other question, you shouldn't be using On Error etc just do:

Try
  Using sr as StreamReader ...
     ...
  End Using
Catch ex as SomeException
...
End Try
ho1
+10 if I could for **you shouldn't be using On Error**
Binary Worrier
+1  A: 

This code:

Using sr As StreamReader = New StreamReader(OpenFile)
    str = sr.ReadToEnd
    sr.Close()
End Using

Is really equivalent to this:

Dim sr As StreamReader = Nothing
Try
    sr = New StreamReader(OpenFile)
    sr.Close() ' notice: unnecessary '
Finally
    sr.Close()
End Try

Keep in mind that code within a Finally block will always execute before the method returns (if it throws an exception of its own, well, then you're in for a world of hurt). So the sr.Close line you have within your Using block is superfluous at best (notice it is blatantly unnecessary in the equivalent code using Try/Finally since sr.Close will be called in the Finally no matter what -- exception thrown or not).

Dan Tao