From Xojo Documentation
|You are currently browsing the old Xojo documentation site. Please visit the new Xojo documentation site!|
Occurs when code tries to access an object that doesn't exist.
A NilObjectException occurs when you use a property or variable to access an object that doesn't exist. For example, when the FolderItem.Constructor method 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 FolderItem.Constructor, 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.
This example tries to open a jpeg file using the FolderItem's Constructor method and display it in an ImageWell. If the pathname passed to the FolderItem 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, the FolderItem's Constructor 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.
f = new FolderItem("/Users/fred/Documents/Fluffy.jpeg")
If Not f.Exists Then
MessageBox("The file " + f.NativePath + "doesn't exist!")
Else // document exists
ImageWell1.Image = Picture.Open(f)
Catch e As NilObjectException
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:
If p = Nil Then
MessageBox("There isn't enough memory available to create the picture.")
// do something with the picture here