Has anyone ever seen an exception thrown when calling close method on any closable object?
I haven't, but it's possible. Imagine if there's an OutputStream
that for some reason hasn't written to the file yet. Well, calling close()
will flush out the data, but if the file is locked - then an IOException
would be raised.
I have - in my unit tests against mocks ;)
Try yanking a USB drive with an open file on it. If it doesn't give an exception I'd be pretty surprised.
Old post and long since answered but here's a real example:
The following code will except out when bufferedWriter.close() is called. This happens because the BufferedWriter's underlying Writer (the FileWriter) has already been closed and when a BufferedWriter closes, it first attempts to flush any data in its buffer to its underlying Writer.
File newFile = new File("newFile.txt");
FileWriter fileWriter = new FileWriter(newFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("Hello World");
fileWriter.close();
bufferedWriter.close();
Note: If there's no data in the buffer [comment out the write() line or add a flush() call] then no exception will be generated
An IOException
will be thrown on close
if the final flush
fails. Possible causes include:
OutputStreamWriter
or similar,I have certainly seen some of these. Others are unlikely.
However, if the data you are writing is important then you should allow for close
failing. For example, if your application is writing out a critical file the file system fills up, your application had better notice this before it replaces the old copy of the file with the truncated version.
Yes, it's not that rare, IMHO if you are working with anything other than non-local disk files.
Close() works if at that point your closable is still valid and open. Many things like pipes, remote files, etc., can die prematurely.
In addition, I have seen code that ignores errors on open and write and still tries to close (e.g., in a finally block).