Oracle added writeBytes(byte[] b) method to the ByteArrayOutputStream class since Java 11. This method takes a byte array and writes it to ByteArrayOutputStream. However, ByteArrayOutputStream extends OutputStream class that defines a write(byte[] b) to do same thing. Why did Java need a new method to do that?
Why did Java 11 add writeBytes(byte[] b) method to the ByteArrayOutputStream class while the write(byte[] b) method did the same?
644 views Asked by MTB At
2
There are 2 answers
4
On
As noted by others, the benefit of the new method is that it isn't declared as throws IOException.
It was added in response to this issue JDK-8180410 "ByteArrayOutputStream should not throw IOExceptions". The stated rationale in the issue is simply that it makes no sense1 to have to write a try ... catch for an exception that will never be thrown. That's it.
They (strictly) didn't need to add it. They added it as a convenience.
1 - As the reporter puts it: "It's contradictive."
ByteArrayOutputStream.writeBytes doesn't throw the unnecessary
IOException.It's a new method specific to the byte array output stream, whereas the other options are inherited from OutputStream and are declared to throw the checked
IOException(which is an unnecessary pain to handle if you know you're writing to a byte array output stream - you don't have a network connection to fail or similar)