Udostępnij za pośrednictwem


How to: Clean up Resources with a Try…Finally Block in Visual Basic

A Finally statement can be used within a Try block to ensure allocated resources are clean. The code in a Finally block runs after the exception-handling code, but before control returns to the calling procedure. The code in a Finally block will run even if your code throws an exception, and even if you add an explicit Exit Function (or Exit Sub) statement within a Catch block.

If you do not need to catch specific exceptions, the Using statement behaves like a Try…Finally block, and guarantees disposal of the resources, no matter how you exit the block. This is true even in the case of an unhandled exception. For more information, see Using Statement (Visual Basic).

To clean up resources with a Finally statement

  • Place the code that you would like executed regardless of exceptions within the Finally block. The following code creates a StreamReader and uses it to read from a file.

    Dim reader As New System.IO.StreamReader("C:\testfile")
    Try
        reader.ReadToEnd()
    Catch ex As System.IO.IOException
        MsgBox("Could not read file")
    Finally 
        'This command is executed whether or not the file can be read
        reader.Close()
    End Try
    

See Also

Tasks

How to: Test Code with a Try…Catch Block in Visual Basic

How to: Check an Exception's Inner Exception

How to: Dispose of a System Resource

Concepts

Exception Handling for Visual Basic 6.0 Users

Reference

Using Statement (Visual Basic)

Other Resources

Exception Handling Tasks