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 ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.