Help needed tracking a NilObject in a recursion

Hi everyone,

I’d like some advice about how to track down a problem I’m having with a recursive folder search. I am using a blog (Recursion: Emptying a Folder – Xojo Programming Blog) as my source for doing a search for folder. Basically I want to find all instances of node_modules folders to do some VueJS housekeeping. The code works most of the time but I keep having a NilObjectException. I am using a Try-Catch block but it’s not able to identify the issue. Here is the code where the exception is being raised. It looks to my (relatively inexperienced) eyes as though f.item(n).NativePath is the thing that is a NilObject but I can’t think why, since I’d been using if clauses to identify these strings. The Try-Catch block just raises another NilObjectException. How can I get more information on this to narrow down what is going on?
Any guidance much appreciated.
Code below:

If f.Directory Then
  For n As Integer = f.Count DownTo 1
    If f.Item(n) <> Nil Then
      // If it's a folder, recurse into it
      If f.item(n).Directory And f.Count <> 0 Then
        Dim f1 As FolderItem = f.item(n)
      End If
      // if the folderitem is not empty and the path is not the original folder then add the pathname to the listbox.
      // Check whether the folder name is the one ("node_modules") set in txtFolderName.Text
        if f.item(n).NativePath.right(Window1.txtFolderName.Text.Length) = Window1.txtFolderName.Text then
          If f.item(n) <> Nil And f.item(n).NativePath <> originfolder Then Window1.lstFolderNames.addRow(f.item(n).NativePath)
        end if
      Catch e As NilObjectException
        MessageBox("Looks like a nil object here:" + f.item(n).NativePath)
      End Try
    End If
End if

Is deleteAllFilesInside the name of your recursive method? If so I’d expect you’d need a continue after calling it, thus:

End If

since you have completed everything you wanted to do with f1.

if f is nil then throws a NilObjectException
if f1 is nil then f.deleteAllFilesInside throws a NilObjectException
they are all outside the try…catch

Thanks for the quick replies folks. These made me realise that there were a number of flaws in my code. Now that I’ve resolved those it seems to work fine.