I am trying to load files in a program I am working on. I am doing this through the use of getClassLoader().getResource(). This works perfectly when the file is able to be found. However, when the file cannot be found it throws a NullPointerException. Shouldn't it be throwing a FileNotFoundException instead, or does getResource() just not throw such an exception?
Here's the code (pretty standard file loading):
public static File loadFile(String path) throws FileNotFoundException
return new File(FileHandler.class.getClassLoader().getResource(path).getFile());
getResource doesn't throw an exception. It returns
null if the resource is not found.
Your code throws the exception when it tries to call
getFile on the null reference returned by
You could do this:
URL resourceURL = FileHandler.class.getClassLoader().getResource(path); if(resourceURL == null) throw new FileNotFoundException(path+" not found"); return new File(resourceURL.getFile());