LoslegenKostenlos loslegen

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

Kurs anzeigen

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() verursachte ArrayIndexOutOfBoundsException zu behandeln.
  • Lass getScore(int) eine ArrayIndexOutOfBoundsException werfen, 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];
	}
}
Code bearbeiten und ausführen