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)热门推荐
1 怎么说祝福语简短
10 生日果酒祝福语简短独特
11 发廊元旦祝福语大全简短
12 新年祝福语长篇文案简短
13 合字的祝福语简短
14 离校退群祝福语简短
15 节日祝福语幽默简短的
16 早安祝福语大全简短励志
17 英文祝福语简短带名字
18 新年给妹妹祝福语简短