Java异常学习三:异常链
package com.jyz.study.jdk.exception;/** * 异常链 * @author JoyoungZhang@gmail.com * */public class ExceptionCause { public static void main(String[] args) throws Exception {test1(); } private static void test1() throws Exception{try{ test2();}catch(NullPointerException ex){//1 Exception bussinessEx = new Exception("packag exception");// bussinessEx.initCause(ex);// throw bussinessEx;//2 throw new Exception("packag exception", ex);//3 throw (Exception)ex.fillInStackTrace().initCause(ex);} } private static void test2(){test3(); } private static void test3(){throw new NullPointerException("str is null"); }}
?
?
- 1和2分别通过initCause()和构造器设置cause。3的出发点和1 2 一样,当能否运行通过?答案是不能,参考http://zy19982004.iteye.com/admin/blogs/1974796?throwable?不能是它自己的?cause。控制台信息
Exception in thread "main" java.lang.Exception: packag exceptionat com.jyz.study.jdk.exception.ExceptionCause.test1(ExceptionCause.java:18)at com.jyz.study.jdk.exception.ExceptionCause.main(ExceptionCause.java:11)Caused by: java.lang.NullPointerException: str is nullat com.jyz.study.jdk.exception.ExceptionCause.test3(ExceptionCause.java:31)at com.jyz.study.jdk.exception.ExceptionCause.test2(ExceptionCause.java:27)at com.jyz.study.jdk.exception.ExceptionCause.test1(ExceptionCause.java:16)... 1 more?
?