開始使用免費開始

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
        ____
	}
}
編輯並執行程式碼