Difference between revisions of "Catch"

From Xojo Documentation

(Usage)
(Sample Code)
 
Line 46: Line 46:
 
Catch e As OutOfBoundsException
 
Catch e As OutOfBoundsException
 
   // The above exception is caught here for you to handle
 
   // The above exception is caught here for you to handle
   ErrorLabel.Value = "Exceeded size of array"
+
   ErrorLabel.Text = "Exceeded size of array"
 
End Try
 
End Try
 
</rbcode>
 
</rbcode>
Line 55: Line 55:
 
Try
 
Try
 
   Var f As New FolderItem("test.txt")
 
   Var f As New FolderItem("test.txt")
   ListBox1.CellValueAt(10, 10) = "Hello"
+
   ListBox1.CellTextAt(10, 10) = "Hello"
 
   
 
   
 
Catch noe As NilObjectException
 
Catch noe As NilObjectException

Latest revision as of 18:47, 1 February 2022

Language Keyword

Used to handle RuntimeException errors in a Try statement.

Usage

Catch [ [ErrorParameter] [As ErrorType] ]

Part Description
ErrorParameter Optional, used to determine the type of runtime exception.
ErrorType Used to 'catch' a particular type of runtime error.

Optional, if used, it must be used with ErrorParameter. If used, the Catch statement will handle only that type of runtime error.

Notes

The Try statement is similar to the Exception statement. Exceptions that occur within the Try block 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.

Local variables that are declared inside a Catch statement exist only within the Catch statement's scope rather than inside the whole method's scope. This means that multiple Catch statements at the same level can use the same exception variable name.

A Try block 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 block.

Sample Code

This example uses the Catch statement to handle an out of range key that is passed to a Dictionary.

Try
Var a(5) As Integer
a(6) = 45 ' Raises an OutOfBoundsException
Catch e As OutOfBoundsException
// The above exception is caught here for you to handle
ErrorLabel.Text = "Exceeded size of array"
End Try

You can also catch multiple exceptions:

Try
Var f As New FolderItem("test.txt")
ListBox1.CellTextAt(10, 10) = "Hello"

Catch noe As NilObjectException
// code
Catch oobe As OutOfBoundsException
// code
End Try

See Also

Exception, Try statements; Finally, Function, Sub statements; RuntimeException error.