把捕获的异常包装成一个新的异常,接着在新的异常里添加对原始异常的引用,最后把这个新异常抛出。
就像是链式反应一样,一个接一个,就叫做java的异常链。
一、代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package error_dao; public class chaintest { /* * test1()抛出喝大了异常 test2()调用test1()捕获喝大了异常 * main方法中,调用test2(),尝试捕获test2()方法抛出的异常 */ public static void main(String[] args) { chaintest ct = new chaintest(); try { ct.test2(); } catch(Exception d) { d.printStackTrace(); } } public void test1() throws drunk_excption { throw new drunk_excption("简直是丧心病狂"); } public void test2() throws drunk_excption { try { test1(); } catch (drunk_excption d) { RuntimeException newExc = new RuntimeException("要出大事啊兄弟"); newExc.initCause(d); throw newExc; } } } |
结果为:
1 2 3 4 5 6 7 |
java.lang.RuntimeException: 要出大事啊兄弟 at error_dao.chaintest.test2(chaintest.java:29) at error_dao.chaintest.main(chaintest.java:13) Caused by: error_dao.drunk_excption: 简直是丧心病狂 at error_dao.chaintest.test1(chaintest.java:22) at error_dao.chaintest.test2(chaintest.java:27) ... 1 more |
做了少许的改动后:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package error_dao; public class chaintest { /* * test1()抛出喝大了异常 test2()调用test1()捕获喝大了异常 * main方法中,调用test2(),尝试捕获test2()方法抛出的异常 */ public static void main(String[] args) { chaintest ct = new chaintest(); try { ct.test2(); } catch(Exception d) { d.printStackTrace(); } } public void test1() throws drunk_excption { throw new drunk_excption("简直是丧心病狂"); } public void test2() throws drunk_excption { try { test1(); } catch (drunk_excption d) { RuntimeException newExc = new RuntimeException(d); throw newExc; } } } |
结果为:
1 2 3 4 5 6 7 |
java.lang.RuntimeException: error_dao.drunk_excption: 简直是丧心病狂 at error_dao.chaintest.test2(chaintest.java:29) at error_dao.chaintest.main(chaintest.java:13) Caused by: error_dao.drunk_excption: 简直是丧心病狂 at error_dao.chaintest.test1(chaintest.java:22) at error_dao.chaintest.test2(chaintest.java:27) ... 1 more |
以上两种就是常用的两种异常写法。
二、总结
记录一下。