Used to handle RuntimeException errors prior to the Exception statement.


  ' Your code
Catch [ errorParameter [ As ErrorType ] ]
  ' Your code to handle the exception
  ' Your code that will execute even if an exception has occurred
End Try




The code that that while executing will results in the Catch section executing should an exception occur.


Optional. This code executes should an exception occur. The optional errorParameter allows you to be specific about the type of exception (IOException, RuntimeException, etc.) you wish to catch. The errorType is also optional but can only be used in conjunction with an ErrorParameter. A Try Catch statement can continue multiple Catch statements that handle different types of exceptions.


Optional. This code that executes regardless of whether or not an exception occurred.

End Try

Signifies the end of the Try Catch statement. The Try keyword here is optional.


The Try statement is similar to the Exception statement. Exceptions that occur within the Try statement are caught by the Catch statement. It has the same syntax as the Exception statement. See the RuntimeException statement or the Runtime Errors theme for descriptions of each type of runtime error.

Unlike the Exception statement, Try statements can be nested. If a Try statement does not handle an exception or re-raises it, it can be handled by the next outermost Try statement, or by the Exception statement itself if there are no containing Try statements.

A Try statement can contain its own Finally statement. The code in the Finally statement will execute regardless of whether or not an exception was raised within the Try statement.

Sample code

This example uses the Catch statement in a window's Opening event handler to handle out of memory exceptions when trying to draw an imported gif image. The variable MyPicture is a global property of type Picture. The picture "Logo" has been added to the Project.

  MyPicture = New Picture(Logo.Width, Logo.Height)
  MyPicture.Graphics.DrawPicture(Logo, 0, 0)
Catch err As OutOfMemoryException
  MessageBox("Insufficient memory to draw the picture!")
End Try

The following example handles an attempt to access a nonexistent value in a Dictionary.

  someValue = myDict.Value("doesn't exist")
Catch err As KeyNotFoundException
  MessageBox("The requested key does not exist.")
End Try

The following catches any exception in the code block:

  Var d As DateTime
  Var day As Integer = d.Day ' NilObjectException will be caught below
Catch e As RunTimeException
  If e IsA EndException Or e IsA ThreadEndException Then
    Raise e ' Re-raise the exception for the framework
  End If

End Try


All project types on all supported operating systems.

See also

Catch, Exception, Finally, Function, Raise, Sub statements; RuntimeException class; Exception Handling topic