Appendix F. Error Handling

This appendix provides information on error handling.

STRUCTURED ERROR HANDLING

A Try block tries to execute some code and reacts to errors. 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 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."

CLASSIC ERROR HANDLING

The On Error statement controls error handlers in Visual Basic classic error handling. You can use structured and classic error handling in the same program but not in the same routine.

The following list briefly describes the On Error statement's four variations:

  • On Error GoTo line — If an error occurs, the program enters error-handling mode and control jumps to the ...

Get Visual Basic® 2010 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.