一.打印栈轨迹的方法
- 主动调用Throwable对象的printStackTrace()=printStackTrace(System.err),printStackTrace(PrintStream),printStackTrace(PrintWriter)中的其中一个。
- 如果一个Exception没有被处理,直接在main方法后面throws,程序退出前将调用异常的printStackTrace()方法,最终是Exception in thread "main" + printStackTrace()
二.栈轨迹
- 栈轨迹显示了"把你带到异常抛出的地点"。
- 上面三个方法调用this.getOurStackTrace()获得栈轨迹;同时Throwable提供了public的方法getStackTrace()获得栈轨迹(实际返回getOurStackTrace().clone())。
- getStackTrace()将返回栈轨迹中元素所构成的数组,其中每一个元素都是一帧。元素0是栈顶元素,栈顶元素为调用序列里的最后一个方法,栈底元素是第一个方法。
package com.jyz.study.jdk.exception; /** * 栈轨迹 * @author JoyoungZhang@gmail.com * */ public class StackTrace { public static void main(String[] args) { test1(); } private static void test1(){ test2(); } private static void test2(){ test3(); } private static void test3(){ throw new NullPointerException("str is null"); } }
Exception in thread "main" java.lang.NullPointerException: str is null at com.jyz.study.jdk.exception.StackTrace.test3(StackTrace.java:24) at com.jyz.study.jdk.exception.StackTrace.test2(StackTrace.java:20) at com.jyz.study.jdk.exception.StackTrace.test1(StackTrace.java:16) at com.jyz.study.jdk.exception.StackTrace.main(StackTrace.java:12)
三.fillInStackTrace方法
- native fillInStackTrace()方法将返回一个Throwable对象,它是通过把当前调用栈信息填入原来那个异常对象儿建立的,所以返回的还是原来的异常。
- 调用此方法的那一行将成为异常新的发生地,有关原来异常发生点的信息会丢失。它的效果等价于捕获一个异常后,重新抛出另外一种异常。两者不同的是,fillInStackTrace后的异常还是原来的异常(只是少了栈轨迹而已);而重新抛出一个异常的话,完全跟原异常信息无关了(当然也没有栈轨迹)。
package com.jyz.study.jdk.exception; /** * 栈轨迹 * fillInStackTrace * @author JoyoungZhang@gmail.com * */ public class FillInStackTrace { public static void main(String[] args) throws Exception { test1(); } private static void test1() throws Exception{ try{ test2(); }catch(NullPointerException ex){ //1 throw (Exception)ex.fillInStackTrace(); //2 throw new Exception(); } } private static void test2(){ test3(); } private static void test3(){ throw new NullPointerException("str is null"); } }
- 1和2的异常栈信息均如图
。不同的是this本身的信息,控制台第一行打印的就是this。
1的栈信息 Exception in thread "main" java.lang.NullPointerException: str is null at com.jyz.study.jdk.exception.FillInStackTrace.test1(FillInStackTrace.java:20) at com.jyz.study.jdk.exception.FillInStackTrace.main(FillInStackTrace.java:13) 2的栈信息 Exception in thread "main" java.lang.Exception at com.jyz.study.jdk.exception.FillInStackTrace.test1(FillInStackTrace.java:21) at com.jyz.study.jdk.exception.FillInStackTrace.main(FillInStackTrace.java:13)