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的結果。