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

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

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

package com.zaixian;

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.zaixian;

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...

上一篇: Java異常 下一篇: Java數據結構