SafeArray creates an array of 10 numbers in which values[i] is i × i + 1. It then reads words until the end of the input; each word is supposed to be an index. For each word it prints the element at that index — but the user may type anything, and the program must never crash:
Integer.parseInt(text)throws aNumberFormatExceptionwhen the word is not a whole number;values[index]throws anArrayIndexOutOfBoundsExceptionwhen the index is not between 0 and 9.
Catch each exception with its own catch block and count the answers given and refused. For the input
3 9 10 two -1 0 4.5
the program prints
values[3] = 10
values[9] = 82
Out of bounds: 10 (valid indexes are 0 to 9)
"two" is not a whole number
Out of bounds: -1 (valid indexes are 0 to 9)
values[0] = 1
"4.5" is not a whole number
Answered 3, refused 4 - and the program never crashed