Provides a way to handle some or all possible errors that may occur in a given block of code, while still running code.
Try tryStatements [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
catchStatements
Required. Statement(s) to handle errors occurring in the associated tryStatement. Can be a compound statement.
If errors occur that the programmer has not handled, Visual Studio for Applications simply provides its normal error message to a user, as if there was no error handling.
The tryStatements argument contains code where an error can occur, while catchStatements contains code to handle any error that does occur. If an error occurs in tryStatements, program control is passed to the appropriate catchStatement for disposition. The exception is an instance of the Exception class or an instance of a class that derives from the Exception class corresponding to the error that occurred in tryStatements. The Exception class instance contains information about the error including, among other things, its number and message.
The following simplified example illustrates the structure of the Try…Catch…Finally statement:
Sub TryExample Dim x As Integer ' Declare variables. Dim y As Integer Try ' Setup structured error handling. x \= y ' Cause a "Divide by Zero" error. Catch e As Exception ' Catch the error. MessageBox.Show e.toString ' Show friendly error message. Finally Beep ' Beep after error processing. End Try End Sub
End Statement | Err Object | Exit Statement | On Error Statement