在异常调用链当中:异常对象创建顺序(栈内进行),和异常堆栈链显示顺序恰好相反(出栈顺序)
源码:
package lsh.element;public class ExceptionChains { public static void main(String[] args) { try { method1(); } catch (Exception2 e) { e.printStackTrace(); } } public static void method1() throws Exception2 { // 靠近栈顶,所以消息先出栈;后实例化 try { method2(); } catch (Exception2 e) { throw new Exception2("New info from method1", e); } } public static void method2() throws Exception2 { // 靠近栈底,所以消息后出栈;先实例化 throw new Exception2("New info from method2"); }}class Exception2 extends Exception { private static final long serialVersionUID = 1L; static { System.out.println("Exception2 - static"); } { System.out.println("Exception2 - instance"); } Exception2(String msg) { super(msg); System.out.println("Exception2 - init"); } public Exception2(String message, Throwable cause) { super(message, cause); System.out.println("Exception2 - init2"); }}
执行结果:
Exceptin2 - staticException2 - instanceException2 - initException2 - instanceException2 - init2lsh.element.Exception2: New info from method1 at lsh.element.ExceptionChains.method1(ExceptionChains.java:16) at lsh.element.ExceptionChains.main(ExceptionChains.java:6)Caused by: lsh.element.Exception2: New info from method2 at lsh.element.ExceptionChains.method2(ExceptionChains.java:21) at lsh.element.ExceptionChains.method1(ExceptionChains.java:14) ... 1 more
以上:上半部分是栈内正常执行顺序;下半部分的异常信息顺序。