-1

How do I catch the null that is thrown if the file object returns null? I keep getting a java.lang.NullPointerException.

public static File getFile() {
        String filePath = JOptionPane.showInputDialog("Enter the full path to           the file you want to open");
        File file = new File(filePath);
        while(!file.exists()) {
            filePath = JOptionPane.showInputDialog("Please enter a valid full path");
        }
        return file;
    }
}
tckmn
  • 57,719
  • 27
  • 114
  • 156
jdj005
  • 11
  • 2
  • You should format your code in a readable format – 3kings Nov 14 '15 at 04:05
  • you need to create the file right? if it doesn't exist – 3kings Nov 14 '15 at 04:06
  • 3
    To answer your question: [TryCatch](https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html). However this is really not how you want to handle it. You probably want to check against `null` with a simple `if`. – Emz Nov 14 '15 at 04:08
  • Note that your `while` loop is bad, since it never changes `file`, so it'll loop forever if the first input is a non-existent file. – Andreas Nov 14 '15 at 04:44
  • Yeah if the file is valid I need to return the file – jdj005 Nov 14 '15 at 05:05

1 Answers1

0

javadocs about public File(String pathname) constructor:

NullPointerException - If the pathname argument is null

so better check filePath is not null, before passing it to new File(String path)

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24