在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中文网其他相关文章!