IllegalCastException

From Xojo Documentation

Class (inherits from RuntimeException)

Caused by an attempt to recast an object and then sending it a message that its original type cannot handle.

Properties
CallStack Message Stack
ErrorNumber Stack
Methods
CallStack Stack

Notes

An IllegalCastException error occurs when you attempt to cast an object to a different type and call a method or access a property belonging only to the original type. For example, if you recast a BevelButton as a PushButton (see the example below) and then call the Pushbutton's Push method, an IllegalCastException will occur because a BevelButton isn't a PushButton and happens not to have a Push method.

Sample Code

This example attempts to cast a BevelButton as a PushButton then call the Push method of the PushButton class. This example assumes that there is a BevelButton called "BevelButton1" in the same window where this code is being called:

Dim c As Control
c = BevelButton1
PushButton(c).Push

When you test this code in the IDE, execution will stop at the last line and display an IllegalCastException error in your Code editor. If you test the code in a standalone app, the application will display a generic error message and quit when the user clicks OK.

You can handle the error by adding an Exception block to your code:

Dim c As Control
c = BevelButton1
PushButton(c).Push
Exception err
If err IsA IllegalCastException Then
MsgBox("Trying to recast a BevelButton as PushButton!")
End If

When you test this code in a standalone application, the message box display a more informative message that does not cause the app to quit.

See Also

RuntimeException class; Function, Raise statements; Nil datatype; Exception, Try statements.