Java: IOException while writing to ByteArrayOutputStream?

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

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

Or are there real situations where a ByteArrayOutputStream can throw an exception?

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

EDIT

As John points out, ByteArrayOutputStream does not declare a throws in the write methods that it defines, however, it inherits write(byte[]) from the OutputStream , and this throws an IOException (it is strange that BAOS will not override this method as it can replace version of the superclass - which writes one byte at a time - with a much more efficient call to arraycopy )

+7
source share
4 answers

Well, ByteArrayOutputStream does not declare that any of its methods throw an IOException except writeTo and close . (I don’t know why close still declares this, to be honest.)

If you have a link of type OutputStream , although you will of course still see throwing announcements.

I would not use an empty catch block - I would choose something like IllegalStateException or a similar exception thrown: this means that you are in a situation that you really do not expect, and something went wrong.

+9
source

I just noticed that ByteArrayOutputStream.write does not actually throw an IOException, but Eclipse complains about an unhandled exception when I use it ... weird.

This is easy to explain. You probably did something like this:

  OutputStream os = new ByteArrayOutputStream(); ... os.write(); 

The "problem" is that you are calling the method as OutputStream.write() , and not as ByteArrayOutputStream.write() . Therefore, the compiler says:

"Ah ... write() on an OutputStream may throw an IOException , so you need to deal with it."

You can not say:

"This particular OutputStream really is a ByteArrayOutputStream ... so we'll let you go."

because JLS does not allow it.

This is one of those extreme cases when, after transcoding to the interface, and not to the implementation class, the next "best practice" returns to bite you.

OK, therefore ...

  • its soft gap, not a complete bite.
  • OutputStream is implemented as a Java class, not a Java interface, but this is not relevant.
  • most compilers don't actually talk to you when compiling your code :-)

+2
source

A typical cliche is throw new RuntimeException(theIOException) in a catch block. If the impossible happens, you will at least learn about it.

+1
source

An exception chain is the best practice in this situation. ie throw a RuntimeException.

+1
source

All Articles