在Java中,fillInStackTrace()是Throwable類別中的重要方法。堆疊追蹤可以幫助確定異常的確切拋出位置。在某些情況下,我們可能需要重新拋出異常並找出它被重新拋出的位置,我們可以在這種情況下使用fillInStackTrace()方法。
<strong>public Throwable fillInStackTrace()</strong>
public class FillInStackTraceTest { public static void method1() throws Exception { throw new Exception("This is thrown from method1()"); } public static void method2() throws Throwable { try { method1(); } catch(Exception e) { System.err.println("Inside method2():"); e.printStackTrace(); throw e.fillInStackTrace(); // <strong>calling fillInStackTrace() method</strong> } } public static void main(String[] args) throws Throwable { try { method2(); } catch (Exception e) { System.err.println("Caught Inside Main method()"); e.printStackTrace(); } } }
Inside method2(): java.lang.Exception: This is thrown from method1() at FillInStackTraceTest.method1(FillInStackTraceTest.java:3) at FillInStackTraceTest.method2(FillInStackTraceTest.java:7) at FillInStackTraceTest.main(FillInStackTraceTest.java:18) Caught Inside Main method() java.lang.Exception: This is thrown from method1() at FillInStackTraceTest.method2(FillInStackTraceTest.java:12) at FillInStackTraceTest.main(FillInStackTraceTest.java:18)
以上是在Java中何時使用fillInStackTrace()方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!