開始使用免費開始

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