Try-catch
捕获一个可能出现的算术异常——被零除,并通过显示一条消息来处理它。您还将看到更多已为您预加载的 BigDecimal 包的用法。
本练习是课程的一部分
Java 的数据类型与异常
练习说明
- 添加一个
try以及try代码块的开始。 - 使用
(ArithmeticException e)捕获ArithmeticException,并开始一个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
____
}
}