开始使用免费开始使用

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
        ____
	}
}
编辑并运行代码