The Java I/O classes java.io.Reader
, java.io.Writer
, java.io.InputStream
, java.io.OutpuStream
and their various subclasses all have a close()
method that can throw an IOException
.
Is there any consensus on the proper way to handle such exceptions?
I have often seen recommendations to just silently ignore them, but that feels wrong, and at least in case of resources opened for writing, a problem while closing the file might mean that unflushed data could not be written/sent.
On the other hand, when reading resources, I'm totally unclear on why close()
might throw and what to do about it.
So is there any standard recommendation?
A related question is Does close ever throw an IOException?, but that is more about which implementations really do throw, not about how to handle the exceptions.
Log it.
You can't really do anything about it (for example write some code that recovers from the error), but its generally worth letting somebody know about it.
Edit:
After further investigation and reading the other comments, I'd say that if you do want to handle it then you're going to have to know details of the implementation. Conversely you probably need to know details of the implementation to decide whether you need to handle it.
Realistically though, I can't think of any examples of streams where the reading or writing would work correctly without throwing an exception, but the closing would.