Throws
As an exception is thrown, a method can elect to handle the exception with a try-catch or throw the exception to its caller (passing the buck). In this exercise, you will see how to throw an exception rather than handle it with try/catch.
Cet exercice fait partie du cours
Data Types and Exceptions in Java
Instructions
- Add a try block around the code to
getScore(3)and print it. - Add a catch block to handle the
ArrayIndexOutOfBoundsExceptioncaused in thegetScore()method. - Have
getScore(int)throwArrayIndexOutOfBoundsExceptioninstead of try/catching the exception.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
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];
}
}