Java: IOException when writing to a ByteArrayOutputStream?

Tony the Pony picture Tony the Pony · Jun 7, 2011 · Viewed 8.8k times · Source

Since ByteArrayOutputStream simply writes to memory, an IOException should never occur. However, because of the contract of the OutputStream interface, all stream operations define IOException in their throws clause.

What is the correct way to "handle" this never-occurring IOException? Simply wrap operations in an empty try-catch block?

Or are there any actual situations where ByteArrayOutputStream could throw an exception?

(See also: How can I handle an IOException which I know can never be thrown, in a safe and readable manner?)

EDIT

As Jon points out, ByteArrayOutputStream doesn't declare a throws clause on the write methods it defines -- however, it inherits write(byte[]) from OutputStream, and that one does throw IOEXception (quite odd that BAOS wouldn't override this method, as it could replace the superclass version -- which writes one byte at a time -- with a far more efficient arraycopy call)

Answer

Jon Skeet picture Jon Skeet · Jun 7, 2011

Well, ByteArrayOutputStream doesn't declare that any of its methods throw IOException except writeTo and close. (I don't know why close still declares it, to be honest.)

If you've got a reference of type OutputStream though, you would still see the throws declarations from that, of course.

I wouldn't use an empty catch block - I'd throw something like IllegalStateException or a similar unchecked exception: it means you're in a situation you really don't expect, and something's gone badly wrong.