Given:
public class Test {
public static void main(String[] args) {
int arr[] = new int[4];
arr[0] = 1;
arr[1] = 2;
arr[2] = 4;
arr[3] = 5;
int sum = 0;
try {
for (int pos = 0; pos <= 4; pos++) {
sum = sum + arr[pos];
}
} catch (Exception e) {
System.out.println("Invalid index");
}
System.out.println(sum);
}
}
What is the result?
A.
12
B.
Invalid Index
12
12
C.
Invalid Index
D. Compilation fails
题解
程序第 11 行的 for 循环的 pos 变量的值为「0,1,2,3,4」,当 pos 变量数值为 4 的时候,第 12 行会因为数组索引超出数组长度,而抛出 ArrayIndexOutOfBoundsException,这个例外会在第 14 行被 catch 接住。因此程序会先输出「Invalid index」,接着再输出 1+2+4+5 的结果。
