Java如何打印异常的堆栈?

时间:2024-03-07 08:18:35

在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();
        }
    }
}
Java

上述代码示例将产生以下结果 -

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

示例-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

上述代码示例将产生以下结果 -

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