Java 多重catch語句的具體使用介紹

來源:互聯網
上載者:User

標籤:第一個   int   數值   except   編譯   because   com   pil   contain   

某些情況,由單個程式碼片段可能引起多個異常。處理這種情況,你可以定義兩個或更多的catch子句,每個子句捕獲一種類型的異常。當異常被引發時,每一個catch子句被依次檢查,第一個匹配異常類型的子句執行。當一個catch語句執行以後,其他的子句被旁路,執行從try/catch塊以後的代碼開始繼續。下面的例子設計了兩種不同的異常類型:
// Demonstrate multiple catch statements.
class MultiCatch {
    public static void main(String args[]) {
        try {
            int a = args.length;
            System.out.println("a = " + a);
            int b = 42 / a;
            int c[] = { 1 };
            c[42] = 99;
        } catch(ArithmeticException e) {
            System.out.println("Divide by 0: " + e);
        } catch(ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index oob: " + e);
        }
        System.out.println("After try/catch blocks.");
    }
}

該程式在沒有命令列參數的起始條件下運行導致被零除異常,因為a為0。如果你提供一個命令列參數,它將倖免於難,把a設成大於零的數值。但是它將導致ArrayIndexOutOf BoundsException異常,因為整型數組c的長度為1,而程式試圖給c[42]賦值。

下面是運行在兩種不同情況下程式的輸出:
C:\>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks.
C:\>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException After try/catch blocks.

當你用多catch語句時,記住異常子類必須在它們任何父類之前使用是很重要的。這是因為運用父類的catch語句將捕獲該類型及其所有子類類型的異常。這樣,如果子類在父類後面,子類將永遠不會到達。而且,Java中不能到達的代碼是一個錯誤。例如,考慮下面的程式:
/* This program contains an error.
A subclass must come before its superclass in a series of catch statements. If not,unreachable code will be created and acompile-time error will result.
*/
class SuperSubCatch {
    public static void main(String args[]) {
        try {
            int a = 0;
            int b = 42 / a;
        } catch(Exception e) {
            System.out.println("Generic Exception catch.");
        }
        /* This catch is never reached because
        ArithmeticException is a subclass of Exception. */
        catch(ArithmeticException e) { // ERROR - unreachable
            System.out.println("This is never reached.");
        }
    }
}

如果你試著編譯該程式,你會收到一個錯誤訊息,該錯誤訊息說明第二個catch語句不會到達,因為該異常已經被捕獲。因為ArithmeticException 是Exception的子類,第一個catch語句將處理所有的面向Exception的錯誤,包括ArithmeticException。這意味著第二個catch語句永遠不會執行。為修改程式,顛倒兩個catch語句的次序。

更多相關知識

Java 多重catch語句的具體使用介紹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.