Java如何打印異常的堆棧?


在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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM