Finally
现在,请修改上一个练习中的 SplitTheBill 计算器,使用 finally 来打印每个人应付的账单金额,即使捕获到了 Exception 也要打印。
本练习是课程的一部分
Java 的数据类型与异常
练习说明
- 添加一个
try,并开始try代码块。 - 完成
catch代码块,并添加一个finally代码块。 - 完成
finally代码块。
交互式实操练习
通过完成这段示例代码来试试这个练习。
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) {
BigDecimal individualBill = new BigDecimal(0);
BigDecimal numPeople = new BigDecimal(people);
// Add a try and the beginning of the try code block
____ ____
individualBill = bill.divide(numPeople);
} catch (ArithmeticException e) {
System.out.println("You didn't provide a positive number of people to split the bill among. Assuming 2 people.");
numPeople = new BigDecimal(2);
individualBill = bill.divide(numPeople);
// End the catch code block and add a finally block
____ ____ ____
System.out.println("Bill for each of " + numPeople + " persons is: " + individualBill);
// End the finally block
____
}
}