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 生日广州男生祝福语简短