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 好听的元旦简短祝福语