Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

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

Community Additions

ADD
Show:
© 2015 Microsoft