|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.
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 aand uses it to read from a file.