今回は例外処理について考えてみましょう。
問題
次のプログラムを実行した場合の出力はどれでしょうか?正しい選択肢を選んでください。
public class ExceptionHandling {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]);
System.out.println("This will not be printed.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds");
} catch (Exception e) {
System.out.println("Generic exception");
} finally {
System.out.println("Finally block executed");
}
}
}
選択肢
- A. Array index out of bounds
- B. Generic exception
- C. Finally block executed
- D. Array index out of bounds
Generic exception - E. 実行時エラー
答えと解説
回答を見る
答え
A. Array index out of bounds
C. Finally block executed
解説
解説のポイント:
- 例外のキャッチと処理の流れ
- finally ブロックの特性
まず、プログラム内で numbers[3]
にアクセスしようとしていますが、配列 numbers
は3つの要素(インデックス0, 1, 2)しか持っていません。
そのため、この行で ArrayIndexOutOfBoundsException
がスローされます。
この例外はキャッチブロック内の最初の catch
セクションで捕捉され、「Array index out of bounds」というメッセージが出力されます。
共有された例外のキャッチが済むと、プログラムは finally
ブロックを実行します。
ここで「Finally block executed」が出力されることが確定します。