CommencerCommencer gratuitement

(Re)lancer

Lorsqu’une méthode lève une exception, la méthode appelante doit la gérer. Pour cela, elle peut utiliser un bloc try/catch ou la relancer. Dans cet exercice, vous allez voir comment une méthode appelante relance une exception.

Cet exercice fait partie du cours

Types de données et exceptions en Java

Afficher le cours

Instructions

  • 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, levez l’Exception.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

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