
在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中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号