Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 自定義異常類,以及 throw 與 throws 的差別

當 JDK 內建的異常型別不足以描述你的錯誤情境時,就該自訂異常類。本文從異常的型別層次談起,示範自定義異常的完整流程,最後釐清 throw 與 throws 這對最常被搞混的關鍵字。

先看清繼承結構

所有異常的共同父類是 Throwable。程式執行期的問題分兩大類:一類是硬體系統或 JVM 造成的故障,Java 定義為 Error,使用者程式無力處理;另一類是程式本身的錯誤,定義為 Exception,可以透過程式設計攔下來並處理。

因此自定義異常必須是 Throwable 的直接或間接子類,實務上建議直接繼承 Exception(受檢異常,編譯器會逼你處理),除非你要的是執行期異常才考慮繼承 RuntimeException。

步驟一:定義自己的異常類

/**
 * 自定義異常類
 */
public class AgeOutOfBound extends Exception {

    public AgeOutOfBound() {
        System.out.print("Sorry, age out of bound !");
    }
}

步驟二:在方法中決定是否拋出

/**
 * 依參數值決定是否拋出異常
 */
public class AgeInput {

    public static void checkAage(int age) throws AgeOutOfBound {   // throws 宣告可能拋出的異常
        if (age > 0 && age < 200) {
            System.out.print("right!");
        } else {
            System.out.println("---------------");
            throw new AgeOutOfBound();                            // throw 實際拋出
        }
    }
}

步驟三:在呼叫端捕捉

public class Demo {

    public static void main(String[] args) {
        int age = 100;
        try {
            AgeInput.checkAage(age);
        } catch (AgeOutOfBound e) {
            System.out.println("Are you rellly :" + age + " years old?");
        }
    }
}

當 age 為 100 時輸出 right!;改為 300 時則依序輸出分隔線、異常類裡的訊息,最後是 catch 區塊的訊息。

throw 與 throws 的差別

throws 用在「方法宣告」上,用來標示這個方法可能把哪些異常往外丟,多個異常以逗號隔開。它本身不處理任何事,只是把責任往上轉移,呼叫者必須自行 try-catch 或繼續往外拋。

static void pop() throws NegativeArraySizeException {
    int[] arr = new int[-3];
}

throw 用在「方法體」中,後面接一個異常物件,執行到該行就立刻中斷,後續程式碼不再執行。若希望上一層能捕捉,被拋出的方法就得搭配 throws 宣告;若要就地處理,則用 try-catch。

class MyException extends Exception {
    String message;

    public MyException(String ErrorMessagr) {
        message = ErrorMessagr;
    }

    public String getMessage() {
        return message;
    }
}

public class Captor {

    static int quotient(int x, int y) throws MyException {
        if (y < 0) {
            throw new MyException("除數不能是負數");
        }
        return x / y;
    }

    public static void main(String args[]) {
        try {
            int result = quotient(3, -1);
        } catch (MyException e) {
            System.out.println(e.getMessage());
        } catch (ArithmeticException e) {
            System.out.println("除數不能為0");
        } catch (Exception e) {
            System.out.println("程序發生了其他的異常");
        }
    }
}

一句話記法:throws 是「我可能会丟」,throw 是「我现在就丟」。另外 catch 的順序由子類到父類排列,把 Exception 放前面會讓其他 catch 永遠到不了,這是編譯器就會擋下的錯誤。

Copyright © Linux教程網 All Rights Reserved