NilObjectException when using ShowOpenFileDialog

I expect that I’m making an obvious mistake, so I’d be grateful for some clarification. I have a file open dialog in my application, which works well in terms of selecting a file, opening it and doing further processing. However I’ve noticed that if for any reason I click the Cancel button in the File Open dialog then it throws a NilObjectException.

I’ve simplified the code but even then the exception is throwing. I think maybe that the try-catch is checking for a nil file object rather than a cancel of the dialog but if so how can I avoid the NilObjectException? As I say some guidance would be appreciated.

Below is the simplified code. Clicking Cancel throws the exception.

  Dim f as FolderItem
  Dim ft as FileType = new FileType()
  ft.Extensions = "xlsx"
  ft.Name = "Excel document"
  f = FolderItem.ShowOpenFileDialog(ft)
Catch e As NilObjectException
  MessageBox("Caught a NilObject Exception")
End Try

Of course it does, as the documentation indicates.

1 Like

That code doesn’t throw an exception for me nor should it.

The only time you should be getting an exception if you later on try to do something with ‘f’ and it is Nil.


Yes, you’re right - my mistake. But the FolderItem.ShowOpenFileDialog will return Nil if you Cancel.

@Ian_Piper have you tried debugging with Project->Break on Exceptions ticked to see where the NOE is occurring? Run under the debugger with that ticked and it will stop on the NOE.

This part will not throw the exception, but f will be nil when you press cancel.

f = FolderItem.ShowOpenFileDialog(ft)
if f.Exists then   // here is where you get the exception

Instead, check for nil first

f = FolderItem.ShowOpenFileDialog(ft)
if f not Nil and f.Exists then

Something to remember, if you’re running the code in the IDE, the debugger will always stop where the exception happens, even if it’s inside a try-catch block. Just press the Continue or one of the Step buttons to move forward.

Now I am curious where the Nil Objection happens. Please let us know.

1 Like

Ah… I did indeed make a mistake. I had put this in my code:

f = FolderItem.ShowOpenFileDialog(ft)
lblFilename.Text = f.NativePath

but this meant that f would be nil if I cancelled the dialog. Hence the NilObjectException. Thanks for your comments; they helped a lot in sorting it.

1 Like

Ah, thank you. That’s more clear now (and normal).