Throws
Wenn eine Exception geworfen wird, kann eine Methode entscheiden, sie mit try/catch zu behandeln oder sie an den Aufrufer weiterzureichen (den Ball weitergeben). In dieser Übung siehst du, wie man eine Exception wirft, statt sie mit try/catch zu behandeln.
Diese Übung ist Teil des Kurses
Datentypen und Exceptions in Java
Anleitung zur Übung
- Füge einen try-Block um den Code ein, der
getScore(3)aufruft und das Ergebnis ausgibt. - Füge einen catch-Block hinzu, um die in der Methode
getScore()verursachteArrayIndexOutOfBoundsExceptionzu behandeln. - Lass
getScore(int)eineArrayIndexOutOfBoundsExceptionwerfen, anstatt die Exception mit try/catch zu behandeln.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
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];
}
}