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.
Este exercício faz parte do curso
Data Types and Exceptions in Java
Instruções do exercício
- 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.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
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];
}
}