Java如何使用catch來處理鏈異常?

2019-10-16 22:29:24

在Java程式設計中,如何使用catch來處理鏈異常?

此範例顯示如何使用多個catch塊處理鏈異常。

package com.yiibai;

public class ChainedExceptions {
    public static void main(String args[]) throws Exception {
        int n = 20, result = 0;
        try {
            result = n / 0;
            System.out.println("The result is" + result);
        } catch (ArithmeticException ex) {
            System.out.println("Arithmetic exception occoured: " + ex);
            try {
                throw new NumberFormatException();
            } catch (NumberFormatException ex1) {
                System.out.println("Chained exception thrown manually : " + ex1);
            }
        }
    }
}

上述程式碼範例將產生以下結果 -

Arithmetic exception occoured: java.lang.ArithmeticException: / by zero
Chained exception thrown manually : java.lang.NumberFormatException

範例-2

以下是在Java中使用catch來處理鏈異常的另一個範例

package com.yiibai;

public class ChainedExceptions2 {
    public static void main(String args[]) throws Exception {
        int n = 20, result = 0;
        try {
            result = n / 0;
            System.out.println("The result is" + result);
        } catch (ArithmeticException ex) {
            System.out.println("Arithmetic exception occoured: " + ex);
            try {
                int data = 50 / 0;
            } catch (ArithmeticException e) {
                System.out.println(e);
            }
            System.out.println("rest of the code...");
        }
    }
}

上述程式碼範例將產生以下結果 -

Arithmetic exception occoured: java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
rest of the code...