throws
例外がスローされたとき、メソッドは try-catch で例外を処理するか、呼び出し元へスローして渡す(責任を委ねる)かを選べます。この演習では、try/catch で処理するのではなく、例外をスローする方法を確認します。
この演習はコースの一部です
Javaにおけるデータ型と例外処理
演習の手順
getScore(3)を実行して結果を出力するコードの周りに try ブロックを追加します。getScore()メソッド内で発生するArrayIndexOutOfBoundsExceptionを処理する catch ブロックを追加します。getScore(int)では、例外を try/catch で処理するのではなく、ArrayIndexOutOfBoundsExceptionをスローするようにします。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
package exceptions;
public class ThrowingExample {
public static int[] scores = { 75, 97, 83 };
public static void main(String[] args) {
// Add a try block
____ {
int lastScore = getScore(3);
System.out.println("Last score:" + lastScore);
// Catch the exception thrown by getScore(int)
} ____ (____ e) {
System.out.println("Tried to access non-existent score");
}
}
// Throw ArrayIndexOutOfBoundsException
public static int getScore(int index) ____ ____ {
return scores[index];
}
}