Introduction to Exception Handling (Visual Basic)

Visual Basic supports both structured and unstructured exception (error) handling. By placing exception handling code in your application, you can handle most of the errors users may encounter and enable the application to continue running. You can use structured and unstructured error handling to plan for potential errors, preventing them from interfering with the application.

Consider using exception handling in any method that uses operators that may generate an exception, or that calls into or accesses other procedures that may generate an exception.

If an exception occurs in a method that is not equipped to handle the exception, the exception is propagated back to the calling method, or the previous method. If the previous method also has no exception handler, the exception is propagated back to that method's caller, and so on. The search for a handler continues up the call stack, which is the series of procedures called within the application. If it fails to find a handler for the exception, an error message is displayed and the application is terminated.

Not

A single method can contain either structured or unstructured exception handling, but not both.

Structured Exception Handling

In structured exception handling, blocks of code are encapsulated, with each block having one or more associated handlers. Each handler specifies some form of filter condition on the type of exception it handles. When an exception is raised by code in a protected block, the set of corresponding handlers is searched in order, and the first one with a matching filter condition is executed. A single method can have multiple structured exception handling blocks, and the blocks can also be nested within each other.

The Try...Catch...Finally statement is used specifically for structured exception handling. For more information, see Structured Exception Handling Overview for Visual Basic.

Unstructured Exception Handling

The On Error statement is used specifically for unstructured exception handling. In unstructured exception handling, On Error is placed at the beginning of a block of code. It then has "scope" over that block; it handles any errors occurring within the block. If the program encounters another On Error statement, that statement becomes valid and the first statement becomes invalid. For more information, see Unstructured Exception Handling Overview (Visual Basic).

See Also

Tasks

Troubleshooting Exception Handling (Visual Basic)

Walkthrough: Structured Exception Handling (Visual Basic)

Reference

On Error Statement (Visual Basic)

Concepts

Types of Errors (Visual Basic)

Structured Exception Handling Overview for Visual Basic

Unstructured Exception Handling Overview (Visual Basic)

Other Resources

Exception Handling Tasks (Visual Basic)