Name

Try...Catch...Finally Statement

Syntax

TrytryStatements

[Catch1 [exception [As type]] [When expression] 
   catchStatements1
[Exit Try]

Catch2 [exception [As type]] [When expression] 
   catchStatements2
[Exit Try]
. . .
Catchn [exception [As type]] [When expression] 
   catchStatementsn]
[Exit Try]

[Finally
   finallyStatements]
End Try

Description

Used to handle runtime errors.

Rules at a Glance

  • The tryStatements, which are required, constitute the Try block and are the statements that VB monitors for errors.

  • The Catchblocks, of which there can be more than one, contain code that is executed in response to VB “catching” a particular type of error within the Try block. Thus, the Catch blocks consist of the error-handlers for the Try block.

  • The phrases exception [As type ] and [When expression ] are referred to as filters in the VB .NET documentation. In the former case, exception is either a variable of type Exception, which is the base class that “catches” all exceptions, or a variable of one of Exception’s derived classes. The When filter is typically used with user-defined errors. (See the upcoming example.)

  • The Exit Try statement is used to break out of any portion of a Try...Catch...Finally block.

  • The optional finallyStatements code block is executed regardless of whether an error occurs (or is caught), unless an Exit Try statement is executed.

Example

The code in the following Try block will raise an error if the user does not enter a number. The Catch block will catch this error.

Try Dim ...

Get VB .NET Language in a Nutshell 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.