NilObjectException Exception

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

# 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 Nilor add an Exception or Try block to the end of the method that handles NilObjectExceptions. Any function's result that is not a String, Integer, Single, Double, Color, or Boolean is an object and should be checked.

# Examples

This example tries to open a PICT 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 AbsolutePath 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.

Dim f as FolderItem
f= GetFolderItem("HD:Images:Logo")
If Not f.exists then
Beep
MsgBox "The file "+f.absolutePath+"doesn't exist!"
else //document exists
If f.MacType="PICT" then
ImageWell1.image=f.OpenAsPicture
end if
end if
Exception err as NilObjectException
MsgBox "Invalid pathname!"

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

Dim p as Picture
p = NewPicture(100,100,32)
If p = Nil then
Beep
MsgBox "There isn't enough memory available to create the picture."
else
//do something with the picture here
end if

# See Also

RuntimeException class; Function, Raise statements; Nil keyword; Exception, Try blocks.