CommencezCommencez gratuitement

Lancer (de nouveau)

Lorsqu'une méthode lance une exception, la méthode appelante doit la gérer. Pour ce faire, elle peut utiliser un bloc try/catch ou la relancer. Dans cet exercice, vous verrez comment une méthode appelante relance une exception.

Cette activité fait partie du cours

Types de données et exceptions en Java

Voir le cours

Instructions de l’exercice

  • Appelez la méthode dineOut() avec 9 personnes pour déclencher l'Exception.
  • Comme la méthode dineOut() ne gère pas l'exception, relancez l'Exception.
  • Comme la méthode splitBill() ne gère pas l'exception, lancez l'Exception.

Exercice interactif pratique

Essayez cet exercice en complétant ce code d’exemple.

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();
		}
	}
}
Modifier et exécuter le code