Appendix F

Error Handling

This appendix provides information on structured error handling that uses the Try Catch statement.

A Try block attempts to execute some code and reacts if errors occur. 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

When an error occurs, the program examines the Catch statements in order until it finds one that matches the current exception. The program executes the finally_statements after the try_statements succeed or after any Catch block is done executing.

THROWING EXCEPTIONS

Use the Throw statement to throw an exception, as in the following code:

Throw New ArgumentException("Width must be greater than zero")

Exception classes provide several overloaded constructors so you can indicate such things as the basic error message, the name of the variable that caused the exception, and an inner exception.

For information on useful exception classes and custom exception classes, see Appendix O, “Useful Exception Classes.”

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.