Try...Catch...Finally Statement
TrytryStatements
[Catch1 [exception
[Astype
]] [Whenexpression
]catchStatements1
[Exit Try] Catch2 [exception
[Astype
]] [Whenexpression
]catchStatements2
[Exit Try] ... Catchn
[exception
[Astype
]] [Whenexpression
]catchStatementsn
] [Exit Try] [FinallyfinallyStatements
] End Try
exception
optional; System.Exception or a derived typeThe exception to catch. If exception
is
omitted or if it is System.Exception
, all
exceptions will be caught. However, if
exception
is omitted, no information about
the exception will be accessible within the Catch
block.
type
optionalThe data type of the exception to be handled by the
Catch
block. Its value can be
System.Exception
or any derived type. If omitted,
its value defaults to System.Exception
, and all
exceptions will be handled.
expression
optional; BooleanA logical expression that defines a condition under which the error
is to be handled by the Catch
block.
Handles runtime errors using Structured Exception Handling.
The tryStatements
, which are required,
constitute the Try
block and are the statements
that VB monitors for errors.
The Catch
blocks, 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.
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.
Multiple Catch
statements can be used. However,
only the first Catch
statement to be true is
executed. This means that multiple Catch
statements should be ordered from most specific to most general, with
a Catch
block handling errors of type
System.Exception
occurring last.