如何在 Java 中打印异常堆栈
问题描述
如何打印异常堆栈?
解决方案
此示例显示如何使用异常类的 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中打印异常堆栈的另一个示例。
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.html