NilObjectException

From Xojo Documentation

Class (inherits from RuntimeException)

Occurs when code tries to access an object that doesn't exist.

Properties
ErrorNumber Message Reason fa-lock-32.png
Methods
Stack StackFrames

Notes

A NilObjectException occurs when you use a property or variable to access an object that doesn't exist. For example, when the GetFolderItem function is passed an invalid pathname, it returns Nil. Certain functions that are designed to return FolderItems on one platform may return Nil when run on other platforms. If your code attempts to access or write to a property of a Nil FolderItem, a NilObjectException will occur.

A function also returns Nil if there isn't enough memory to load the object. For example, if you tried to load a large picture into memory but your application didn't have enough RAM left to load the picture, the function used to load the picture would return Nil.

Immediately after calling a function that returns an object (like GetFolderItem, for example) you should check the object to see if it is Nil or add an Exception or Try block to the end of the method that handles NilObjectExceptions. Any function's result that is not a data type is an object and should be checked.

Sample Code

This example tries to open a jpeg file using GetFolderItem and display it in an ImageWell. If the pathname passed to GetFolderItem is invalid, it returns Nil. The NilObjectException is handled in the Exception block which is after the last "regular" line of the method.

If the pathname is valid, but the item does not exist, GetFolderItem returns a valid FolderItem whose NativePath property is equal to the pathname. You should check the Exists property of the FolderItem to determine whether the file exists before trying to do something with the FolderItem.

This code, in other words, checks for two different problems — invalid pathname and valid path to a nonexistent file.

Var f As FolderItem
Try
f = FolderItem.ShowOpenFiledialog(FileTypes1.jpeg) // defined in the File Types editor
If Not f.Exists Then
Beep
MessageBox("The file " + f.NativePath + "doesn't exist!")
Else // document exists
ImageWell1.Image = Picture.Open(f)
End If
Catch e As NilObjectException
MessageBox("Invalid pathname!")
End Try

The following example creates a new, empty picture. If there isn't enough memory to create the picture, Nil will be returned by the Picture constructor. The example code checks for this and informs the user:

Var p As New Picture(10000, 10000)
If p = Nil Then
Beep
MessageBox("There isn't enough memory available to create the picture.")
Else
// do something with the picture here
End If

See Also

RuntimeException class; Function, Catch, Raise statements; Nil datatype; Exception, Try statements; UserGuide:Exception Handling topic