Java中什么时候使用fulInStackTrace()方法
fillInStackTrace()是Java中Throwable类的重要方法。堆栈跟踪对于确定在何处抛出异常很有用。在某些情况下,我们需要重新抛出异常并找出重新抛出的异常,在这种情况下,我们可以使用fillInStackTrace()方法。
语法
public Throwable fillInStackTrace()
示例
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(); //调用fillInStackTrace()方法
}
}
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)热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志