I\'ve see this sort of thing in Java code quite often...
try
{
fileStream.close();
}
catch (IOException ioe)
{
/* Ignore. We do not care. */
}
You would care if the close()
method flushes written content from a buffer to the filesystem, and that fails. e.g. if the file you're writing to is on a remote filesystem that has become unavailable.
Note that the above re. flushing applies to any output stream, not just files.
I would at the very least log the exception.
I've seen it happen occasionally, if the attempt to close the file fails due to it not being able to flush the data. If you just swallow the exception, then you've lost data without realizing it.
Ideally, you should probably swallow the exception if you're already in the context of another exception (i.e. you're in a finally block, but due to another exception rather than having completed the try block) but throw it if your operation is otherwise successful. Unfortunately that's somewhat ugly to sort out :(
But yes, you should at least log it.
The most common close() problems are out-of-disk space or, as Brian mentioned, a remote stream that's gone poof.
NOTE:
You should really see something like (note: I haven't compile-checked this)
SomeKindOfStream stream = null;
Throwable pending = null;
try {
stream = ...;
// do stuff with stream
} catch (ThreadDeath t) {
// always re-throw thread death immediately
throw t;
} catch (Throwable t) {
// keep track of any exception - we don't want an exception on
// close() to hide the exceptions we care about!
pending = t;
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
if (pending == null)
pending = e;
}
}
if (pending != null) {
// possibly log - might log in a caller
throw new SomeWrapperException(pending);
// where SomeWrapperException is unchecked or declared thrown
}
}
Why all this?
Keep in mind that Java can only track one "pending" exception at a time. If the body of the main try block throws an exception, and the close() in the finally throws an exception, the only thing you'll know about is the close().
The above structure does the following:
To do the above, I usually use the template method pattern to create the exception management and then override a doWork() method that is the body of the try.