From Xojo Documentation

You are currently browsing the old Xojo documentation site. Please visit the new Xojo documentation site!

Language Keyword

Used to handle RuntimeException errors prior to the Exception statement.


// Your code
Catch [ErrorParameter] [As ErrorType]
//exception handlers
[ Finally ]
//code that executes even if runtime exceptions were raised
End [Try]

Part Description
ErrorParameter Optional, used to determine the type of runtime exception.
ErrorType Optional, if used, it must be used with ErrorParameter. Used to '“catch” a particular type of runtime error. If used, the Try statement will handle only that type of runtime error.


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

See Also

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