Exception 物件
一段程式碼拋出多個例外並不罕見。處理這種情況的一種作法是以 try-catch 捕捉所有例外,然後使用 Exception 物件判斷發生了什麼問題,並從 Exception 輸出資訊以協助除錯。
在這裡,你會再次修改 SplitTheBill 應用程式,去 catch 一個通用的 Exception,並使用 Exception 物件中的資料來了解問題的成因。Exception 物件包含許多有用資訊,包括導致問題的方法追蹤(trace)。
本練習屬於課程
Java 的資料型別與例外狀況
練習說明
- 在 catch 區塊中,使用
catch (Exception e)來攔截任何Exception。 - 在
catch區塊中,使用Exception物件參考(e)與getClass()方法,顯示所捕捉例外的型別(類別)。 - 使用
Exception物件參考(e)與getMessage()方法,列印例外的訊息。 - 使用
Exception物件參考(e)與printStackTrace()方法,將「stack trace」列印到輸出串流。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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) {
try {
BigDecimal numPeople = new BigDecimal(people);
BigDecimal individualBill = bill.divide(numPeople);
System.out.println("Bill for each person is: " + individualBill);
// Catch any exception
} catch (____ ____) {
System.out.println("You didn't provide a positive number of people to split the bill among.");
// Print the type (class) of exception
System.out.println("Type of exception: " + ____.____());
// Print the exception message
System.out.println(____.____());
// Print the stack trace
____.____();
}
}
}