如何在 Java 中列印 Exception 的堆疊



問題描述

如何列印 Exception 的堆疊?

解決方案

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

public class Main{
   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 Main.main(Main.java:11)

以下是如何在 Java 中列印 Exception 的堆疊的另一個示例。

public class Demo {
   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)
java_exceptions.htm
廣告
© . All rights reserved.