I’m reading the book Java™ I/O, 2nd Edition and there’s this code:
try {
byte[] b = new byte[10];
System.in.read(b);
}
catch (IOException ex) {
System.err.println("Couldn't read from System.in!");
}
Quoting from the book:
“..there’s nothing to stop you from trying to read more data into the
array than will fit. If you do this, read( ) throws an
ArrayIndexOutOfBoundsException..”
But when I run this code and enter more then 10 characters, no ArrayIndexOutOfBoundsException is thrown; why is that the case?
Your book is wrong and it is also poorly expressed. The following two statements are mutually contradictory:
I don’t know why Elliotte Rusty Harold thinks an exception is ‘nothing to stop you’. It does stop you, and that is its purpose.
The truth of it is that
InputStream.read()will read at least 1 and at mostb.lengthbytes, unless it detects EOS instead and returns -1.If you use the
read(byte[] buffer, int offset, int length)overload it will throwIndexOutOfBoundsExceptionif “off[set] is negative, len[gth] is negative, or len[gth] is greater than b[uffer].length – off[set]”.