CommencerCommencer gratuitement

Try-catch

Interceptez une éventuelle exception arithmétique — division par zéro — et gérez-la en affichant un message. Vous allez également voir un autre usage du package BigDecimal, déjà préchargé pour vous.

Cet exercice fait partie du cours

Types de données et exceptions en Java

Afficher le cours

Instructions

  • Ajoutez un try et le début du bloc de code try.
  • Interceptez l’ArithmeticException avec (ArithmeticException e) et commencez un bloc de code catch.
  • Terminez le bloc de code catch.

Exercice interactif pratique

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

class SplitTheBill {
	public static void main(String[] args) {
		BigDecimal bill = new BigDecimal(125.50);
		computeEachBill(bill, 5);
		computeEachBill(bill, 0);
	}

	public static void computeEachBill(BigDecimal bill, int people) {
		// Add a try and the beginning of the try code block
		____ ____
			BigDecimal numPeople = new BigDecimal(people);
			BigDecimal individualBill = bill.divide(numPeople);
			System.out.println("Bill for each person is: " + individualBill);
			// End the try code block and catch a possible ArithmeticException
        ____ ____ (ArithmeticException e) ____
			System.out.println("You didn't provide a positive number of people to split the bill among.");
			// End the catch code block
		____
	}
}
Modifier et exécuter le code