Try-catch
Перехопіть можливий арифметичний виняток — ділення на нуль — і обробіть його виведенням повідомлення. Ви також матимете змогу побачити додаткове використання пакета BigDecimal, який уже завантажено для вас.
Ця вправа є частиною курсу
Типи даних і винятки в Java
Інструкції до вправи
- Додайте
tryі початок блоку кодуtry. - Перехопіть
ArithmeticExceptionза допомогою(ArithmeticException e)і почніть блок кодуcatch. - Завершіть блок коду
catch.
Інтерактивна практична вправа
Спробуйте виконати цю вправу, доповнивши цей зразок коду.
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
____
}
}