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?
try { try(FileInputStream ....) { /* do stuff */ } } catch (IOException e) { ... }
is much less verbose than your proposal. You don't get to differentiate between an error on closing and an error during reading, is the catch: but ask yourself -- what could cause an error during closing that wouldn't also cause one while reading?FilterInputStream
and catches any exception occurring duringclose
, which is also much less verbose than your example code, and doesn't have the disadvantage of losing the ability to distinguish important and unimportant errors.