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