LoslegenKostenlos loslegen

(Erneut) Werfen

Wenn eine Methode eine Exception wirft, muss die aufrufende Methode diese behandeln. Sie kann die Exception per try/catch abfangen oder erneut weiterwerfen. In dieser Übung siehst du, wie eine aufrufende Methode eine Exception erneut weiterwirft.

Diese Übung ist Teil des Kurses

Datentypen und Exceptions in Java

Kurs anzeigen

Anleitung zur Übung

  • Rufe die Methode dineOut() mit 9 Personen auf, um die Exception auszulösen.
  • Da die Methode dineOut() die Exception nicht behandelt, wirf die Exception erneut.
  • Da die Methode splitBill() die Exception nicht behandelt, wirf die Exception.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

public class RethrowingExample {

	public static void main(String[] args) {
		try {
			// Trigger the exception by calling dineOut with 9 people
			dineOut(____, 50.00);
		} catch (Exception e) {
			System.out.println("Atempting to divide bill with too many diners");
		}
	}

	// Rethrow the Exception
	public static void dineOut(int people, double bill) ____ ____ {
		double each = splitBill(bill, people);
		System.out.println("Bill for each person: " + each);
	}

	// Throw the Exception
	public static double splitBill(double bill, int people) ____ ____ {
		if (people < 3) {
			return bill / people;
		} else {
			throw new Exception();
		}
	}
}
Code bearbeiten und ausführen