O'Reilly logo

Visual Basic 2012 Programmer's Reference by Rod Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

STRUCTURED ERROR HANDLING

Visual Basic .NET uses the Try Catch block to provide structured error handling. The syntax is as follows:

Try
    try_statements ...
[Catch ex As exception_type_1
    exception_statements_1 ...
]
[Catch ex As exception_type_2
    exception_statements_2 ...
]
...
[Catch
    final_exception_statements ...
]
[Finally
    finally_statements ...
]
End Try

The program executes the code in the try_statements block. If any of that code throws an exception, the program jumps to the first Catch statement.

If the exception matches exception_type_1, the program executes the code in exception_statements_1. The exception type might match the Catch statement’s exception class exactly, or it might be a subclass of the listed class. For example, suppose that the code in the try_statements block performs a calculation that divides by zero. That raises a DivideByZeroException. That class inherits from the ArithmeticException class, which inherits from SystemException, which inherits from Exception. That means the code would stop at the first Catch statement it finds that looks for DivideByZeroException, ArithmeticException, SystemException, or Exception.

If the raised exception does not match the first exception type, the program checks the next Catch statement. The program keeps comparing the exception to Catch statements until it finds one that applies, or it runs out of Catch statements.

CATCH CONTROL
Arrange Catch statements so the most specific come first. Otherwise, a more general ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required