Java – Ignore exception when closing a resource such as a file

exceptionsjava

From Effective Java 2e by Joshua Bloch,

An example of the sort of situation where it might be appropriate to ignore an
exception is when closing a FileInputStream. You haven’t changed the state of
the file, so there’s no need to perform any recovery action, and you’ve already
read the information that you need from the file, so there’s no reason to abort the
operation in progress. Even in this case, it is wise to log the exception, so that you
can investigate the matter if these exceptions happen often.

Is it wise to always ignore that exception, as suggested. The code then would look like,

FileInputStream stream = null;
try {
    stream = new FileInputStream("foo.txt");
    // do stuff
} finally {
    if (null != stream) {
        try {
            stream.close();
        } catch (IOException e) {
            LOG.error("Error closing file. Ignoring this exception.", e);
        }
    }

which is much more verbose than

try (FileInputStream stream = new FileInputStream("foo.txt")) {
    // do stuff
}

But is the extra verbosity worth ignoring the exception from closing the file? Is it better to ignore the exception since there's nothing to be done? Should the same approach be used with resources other than a file, such as a database connection?

Best Answer

The reason, which as I recall Bloch explains, is that the interesting Exception is the original one thrown from within the try block. Any Exception thrown within the finally block will hide the original Exception.

Imagine that the ur-Exception is because the File is on a network and the network is down. That's the more informative Exception that you want to throw. But that problem also affects the close() , and you don't want the 2nd exception to "get in the way".

Note this explanation was in V1 of his book...

Added The following code proves the point:

try {
  throw new Exception("in try, here is the ur-Exception");
}
finally {
  throw new Exception("in finally");
}

The second, "in finally" Exception, is the one you will see, hiding the original Exception.

Related Topic