We recommend using Visual Studio 2017
This documentation is archived and is not being maintained.

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")
    Catch ex As System.IO.IOException
        MsgBox("Could not read file")
        'This command is executed whether or not the file can be read
    End Try