I want to build a data structure where I would store all the files from the file-system. For that I have a class directoryNode:
class directoryNode{
    private String name;
    private String path;
    File file;
    //This List Stores the sub-directories of the given Directory.
    private List<directoryNode> subDirectories = new ArrayList<directoryNode>();
    //This List stores the simple files of the given Directory
    private List<String> fileNames = new ArrayList<String>();
    //The Default Constructor.
    directoryNode(File directoryName){
        this.name = directoryName.getName();
        this.path = directoryName.getPath();
        this.file = directoryName;
        //A Function to build this directory.
        buildDirectory();
    }
    File[] filesFromThisDirectory;
    private void buildDirectory(){
        //get All the files from this directory
        filesFromThisDirectory = file.listFiles();
        try{
            for(int i = 0 ; i < filesFromThisDirectory.length ; i++){
                if(filesFromThisDirectory[i].isFile()){
                    this.fileNames.add(filesFromThisDirectory[i].getName());
                } else if(filesFromThisDirectory[i].isDirectory()){
                    directoryNode Dir = new directoryNode(filesFromThisDirectory[i]);
                    this.subDirectories.add(Dir);
                }
            }
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
}
My Program Works fine but I get some weird behavior when I don't use the try- Catch block in the buildDirectory() Function. Build Function recursilvely builds the structure for the list of files as written in the code.
when I do:
directoryNode d1 = new directoryNode(new File("/"));
when try-Catch is there , program works fine but if I remove the try catch block : i get an error after executing it for some time: The error that I get is :
 Exception in thread "main" java.lang.NullPointerException
  at directoryNode.buildDirectory(myClass.java:47)
  at directoryNode.<init>(myClass.java:22)
  at directoryNode.buildDirectory(myClass.java:55)
  at directoryNode.<init>(myClass.java:22)
  at directoryNode.buildDirectory(myClass.java:55)
  at directoryNode.<init>(myClass.java:22)
  at myClass.main(myClass.java:75) 
but when I run :
  directoryNode d1 = new directoryNode(new File("/home/neeraj"));
With or without try - catch block , I the program runs fine without any error. Why is this so ? Why do I get different results in these these scenarios?
 
     
    