Do not ignore IOException when calling close on Outputstreams/Writers

As a good Java Programmer you should close your resources in a finally block, most programmers do so.

But what you can see very often is that the close-call is surrounded by a catch block catching IOExceptions and irgnoring them, e.g.

OutputStream os = …
try {
while (…) {
os.write(…);
}
} finally {
try {
os.close();
} catch (IOException e) { /* ignore it */  }

}

What’s wrong with that code?

When getting the Outputstream/Writer as argument (or even explicitly intantiating your own) you have most of the time a BufferedOutputStream/BufferedWriter. These classes write the data to the underlying Stream/Writer if their buffers are filled or flush() or close() is called on them.

That means that the remaining data in the buffer would be written when calling flush()/close().

So in the example above you’d have a corrupted file wothout noticing it.

So what’s the solution? You should never catch and ignore IOExceptions when writing to resources because they indicate that your file does not contain all the data you intended to write to it.

Advertisements
This entry was posted in Java, Tips. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s