TheNewGuy TheNewGuy - 6 months ago 58
Java Question

getClassLoader().getResource() throwing NullPointerException? Why not FileNotFoundException?

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());
}

//somewhere else
loadFile("data/xt.txt");


if xt.txt exists, the code works fine. If not, it throws a NullPointerException. I can easily modify my code to handle the NullPointerException, but I just can't think of why it's returning null in the first place instead of FileNotFound.

Answer

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 getResource.

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());