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?开发者_JS百科
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
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!)
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 (notice it is unnecessary in the equivalent code using Try
/Finally
since sr.Close
will be called in the Finally
no matter what -- exception thrown or not).
精彩评论