拋出

Java 的資料型別與例外狀況

Jim White

Java Developer

處理選項

  • 受檢例外需「處理」
    • 「處理」執行期例外是可選的
  • 「處理」{{1}} 的兩種方式
    • 用 try/catch 捕捉 Exception,並寫程式碼解決問題
    • 「拋出」例外
  • try/catch 是處理例外的首選方式
    • 但不一定可行,有時集中處理更好
Java 的資料型別與例外狀況

throws 關鍵字

  • 在任何方法上使用 throws,把例外傳回呼叫端方法
    • 相對於在該方法內處理例外
    • 稱為「拋出例外」或「passing-the-buck」
    • 把處理例外的責任交給呼叫者
  • throws 後用逗號列出多個例外型別
    • 表示呼叫端可能需預期的例外型別
public static void someMethod() throws IndexOutOfBoundsException, 
NegativeArraySizeException, NullPointerException {
  // method code
}
Java 的資料型別與例外狀況
throws 範例

一般用 try-catch 處理 Exception

public static void main(String[] args) {
  someMethod();
}
public static void someMethod(){
  try {
    ArrayList<String> games
      = new ArrayList<String>();
    games.add("Monopoly");
    games.add("Chess");
    games.get(3);
  } catch (IndexOutOfBoundsException e) {
    System.out.println(
   "Oops - trying to get non-existent item");
  }
}

用 throws 處理 Exception

public static void main(String[] args) {
  try {
    someMethod();
  } catch (IndexOutOfBoundsException e) {
    System.out.println(
   "someMethod tried to get non-existent item");
  }
}
public static void someMethod()
      throws IndexOutOfBoundsException {
  ArrayList<String> games
    = new ArrayList<String>();
  games.add("Monopoly");
  games.add("Chess");
  games.get(3);
}
Java 的資料型別與例外狀況

何時使用 throws

  • 「passing-the-buck」或拋出例外通常是要避免的
    • 較佳作法通常是在發生處用 try-catch 處理
  • 但選擇拋出而非 try-catch 的理由包括:
    • 發生例外的方法可能不知道如何復原
    • 集中處理可減少重複的 try/catch 程式碼

拋出例外通常搭配自訂例外使用

1 Photo from https://unsplash.com/@philipparosetite
Java 的資料型別與例外狀況

捕捉並再拋出

  • Exception 可以被「再拋出(rethrow)
    • 呼叫端也用 throws,而非寫 try/catch
  • main 再拋出會讓應用程式停止

例外可再拋出給呼叫端方法

Java 的資料型別與例外狀況

再拋出範例

public class RethrowExample {
    public static void main(String[] args) {
        try {
            method1(0);
        } catch (ArithmeticException e) {
            System.out.println("Oops - tried a bad quotient");
        }
    }
    public static void method1(int divisor) throws ArithmeticException {
        method2(divisor);
    }
    public static void method2 (int divisor) throws ArithmeticException {
        int z = 5/divisor;
        System.out.println(z);
    }
}
Java 的資料型別與例外狀況

一起來練習吧!

Java 的資料型別與例外狀況

Preparing Video For Download...