在Java編程中,如何列印異常的堆疊?
此示例顯示如何使用異常類的printStack()
方法列印異常的堆疊。
package com.zaixian;
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.zaixian.PrintStackTrace.main(PrintStackTrace.java:13)
示例-2
以下是Java中列印異常堆疊的另一個例子。
package com.zaixian;
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)