Catch provides a mechanism for retrieving an exception object that was set using the Throw function.
Public Function Catch( ByRef Ex As Exception, Optional ByVal Err As ErrObject ) As Boolean
Returns True if an exception has been caught, setting the ex parameter to the exception object. By retrieving an exception object, the error that occurred can be determined along with any specific details included. In order to catch an exception, error trapping must be used as normal. During error trapping procedures, a call to Catch will attempt to retrieve an exception, returning an indication on whether an exception was caught.
If Throw was not used to raise an error, then the ErrObject must be passed into the function to retrieve the error information. This is because each loaded module (dll, exe, ...) will have its own ErrObject, so VBCorLib has no way of retrieving the error information for modules other than itself. If errors outside of VBCorLib are created using Throw, then the ErrObject does not need to be passed into the Catch function.
If the source of the error will always be from VBCorLib then the ErrObject does not need to be supplied. If the source is not VBCorLib or is unknown, then pass in the ErrObject. Passing in the ErrObject will not affect catching exceptions thrown by VBCorLib.
To clear an existing exception, call Catch and pass in Nothing as the exception variable.
On Error Goto errTrap Throw NewFileNotFoundException("Could not find your file.") '... code errTrap: Dim ex As Exception If Catch(ex) Then If TypeOf ex Is FileNotFoundException Then MsgBox "You will need to enter another filename." Else MsgBox "Error: " & ex.Message End If End IfOnce an exception has been caught, it can be inspected to determine the appropriate course of action.
The error trap section is a typical implementation of catching a VBCorLib exception.
If an error is raised using the Throw function, then the exception object will remain ready to be caught until Catch is called. This is similar to using On Error Resume Next and not clearing any errors that may occur. The ErrObject will contain any error information until some event clears it. This can lead to problems later on in the code when an exception is checked using Catch, and an older exception is still set. The exception may need to be cleared to prevent unwanted exceptions from being caught.
Project CorLib Overview
Class ExceptionMethods Overview