Search code examples
javastreaminputstreamioexceptionfclose

Should I close a JarFile if it throws an I/O error when opening it? (Do the general rules for handling streams apply?)


new JarFile(path) can trow an I/O exception.

If that happens, and I catch the exception, should I close it? (I guess the real question is, is there anything to close?)

The other question is: if it works, should I clean up? I.e., do the general rules for dealing with streams apply?

Sorry if the question is a bit naff; I'm new to dealing with JarFile (and haven't really used streams in the past, either).


Solution

  • There is nothing to close if new JarFile(path) throws an IOException:

    JarFile file = null;
    
    try {
        file = new JarFile("does/not/exist");
    } catch (IOException e) {
        System.out.println(file); //Prints out null
    }
    
    try {
        file.close(); //Throws NullPointerException
    } catch (IOException e) {
        e.printStackTrace();
    }