Name
Try...Catch...Finally Statement
Syntax
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
Description
Used to handle runtime errors.
Rules at a Glance
The
tryStatements, which are required, constitute theTryblock 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 theTryblock. Thus, theCatchblocks consist of the error-handlers for theTryblock.The phrases
exception[Astype]and[Whenexpression]are referred to as filters in the VB .NET documentation. In the former case,exceptionis 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. TheWhenfilter is typically used with user-defined errors. (See the upcoming example.)The
ExitTrystatement is used to break out of any portion of aTry...Catch...Finallyblock.The optional
finallyStatementscode block is executed regardless of whether an error occurs (or is caught), unless anExitTrystatement 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access