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
____
}
}