I recently encountered something strange when assigning a FolderItem in a Window Open event.
Dim f as folderitem
f = SpecialFolder.Desktop.child("test").child("test.zip")
If f <> nil then
// do things //
When /Desktop/test/test.zip does not exists, it throws an NIL object exception at the code line f = SpecialFolder.Desktop.child(“test”).child(“test.zip”)
The code above shouldn’t give any error at all, not?
Of course I can catch it with a try/catch but imo the above should work fine.
[quote=326256:@Christoph De Vocht]True, but the thing is … it throws the error at the f = SpecialFolder.Desktop.child(“test”).child(“test.zip”) code line.
It doesn’t even come to checking for it being Nil.[/quote]
It is because the subfolder test does not exist ; yet you try to make it a child.
Um, guys… that line should not throw an exception (unless SpecialFolder.Desktop is bad). Assuming SpecialFolder.Desktop is non-Nil and exists, then SpecialFolder.Desktop.Child(“test”) will be non-Nil. It may or may not exist, but worst case, SpecialFolder.Desktop.Child(“test”).Child(“test.zip”) will return Nil, but not throw an exception.
I’m surprised that 90% of the posts on this thread either totally misunderstood the poor OP’s question or gave the wrong answer. There is no bug, this is intended and also very, very obvious if you’ve worked with REAL/Xojo any amount of time. Jeff Tullin got it right but everyone seemed to ignore it. I read this forum a lot less in the past year because of all this false information and wrong answers.
f = SpecialFolder.Desktop.child(“test”).child(“test.zip”) is doing multiple things in sequential order like Michel said. SpecialFolder.Desktop returns the Desktop folder item and it always exists. It then performs the method child(), and if that doesn’t not exist it doesn’t return Nil but a non-existent FolderItem, which is legal and often desired.
Now, maybe Xojo doesn’t doc it carefully enough (they probably do), but a FolderItem that is DEFINED but does not exist on the File System throws an exception when you try to perform the child() method. Of course a Nil Object Exception is worded falsely, but it is the best type of exception to call it and have thrown. When you think about this, it makes perfect sense and give Xojo reliability implementing it this way.
That is what’s happening here. Don’t call child() on anything other than a FolderItem that not only is not Nil but also Exist=True. And when you chain child() methods, you expose yourself to this type of thing. And don’t try-catch, that’s bad practice. Code it right.
Lesson: don’t chain your FolderItem.Child() methods. Bad practice.