(重新)拋出
當一個方法拋出例外時,呼叫它的方法必須處理該例外。要處理它,可以用 try/catch 捕捉例外,或是把它重新拋出。本練習中,你將看到呼叫方法如何重新拋出例外。
本練習屬於課程
Java 的資料型別與例外狀況
練習說明
- 使用 9 個人呼叫
dineOut()方法,以觸發Exception。 - 由於
dineOut()方法沒有處理該例外,請重新拋出Exception。 - 由於
splitBill()方法沒有處理該例外,請拋出Exception。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class RethrowingExample {
public static void main(String[] args) {
try {
// Trigger the exception by calling dineOut with 9 people
dineOut(____, 50.00);
} catch (Exception e) {
System.out.println("Atempting to divide bill with too many diners");
}
}
// Rethrow the Exception
public static void dineOut(int people, double bill) ____ ____ {
double each = splitBill(bill, people);
System.out.println("Bill for each person: " + each);
}
// Throw the Exception
public static double splitBill(double bill, int people) ____ ____ {
if (people < 3) {
return bill / people;
} else {
throw new Exception();
}
}
}