Java如何列印異常的堆疊?

2019-10-16 22:29:32

在Java程式設計中,如何列印異常的堆疊?

此範例顯示如何使用異常類的printStack()方法列印異常的堆疊。

package com.yiibai;

public class PrintStackTrace {
    public static void main(String args[]) {
        int array[] = { 20, 20, 40 };
        int num1 = 15, num2 = 10;
        int result = 10;
        try {
            result = num1 / num2;
            System.out.println("The result is" + result);

            for (int i = 5; i >= 0; i--) {
                System.out.println("The value of array is" + array[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

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

The result is1
java.lang.ArrayIndexOutOfBoundsException: 5
    at com.yiibai.PrintStackTrace.main(PrintStackTrace.java:13)

範例-2

以下是Java中列印異常堆疊的另一個例子。

package com.yiibai;

public class PrintStackTrace2 {
    public static void main(String[] args) {
        try {
            ExceptionFunc();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static void ExceptionFunc() throws Throwable {
        Throwable t = new Throwable("This is new Exception in Java...");

        StackTraceElement[] trace = new StackTraceElement[] {
                new StackTraceElement("ClassName", "methodName", "fileName", 5) };
        t.setStackTrace(trace);
        throw t;
    }
}

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

java.lang.Throwable: This is new Exception in Java...
    at ClassName.methodName(fileName:5)