一直觉得异常是一个过不去的坎,因为挺难理解的。
对着慕课网老师的示例,手动敲了代码,并一步步加上syso跟踪,终于对异常throw/throws有更深的理解,现在把验证代码和注释贴上来,希望和有疑惑的同学一起交流。
package com.imooc.season3; public class ThrowDemo extends Exception { //TODO: 自定义Java Exception ,继承Exception父类 public ThrowDemo(){ //construtor函数构造器,无参 } public ThrowDemo(String s){ super(s); System.out.println("Here is ThrowDemo(String s)"); } }
package com.imooc.season3; public class ThrowDemoTest { public void test01() throws ThrowDemo{ //throws declaration声明该方法有异常抛出 System.out.println("step02:Reach test01,new ThrowDemo 初始化函数构造器--》ThrowDemo异常对象,并抛出throw e"); throw new ThrowDemo("test01抛出异常"); //throw 抛出异常的动作 } public void test02(){ try { System.out.println("step01:准备运行test01"); test01(); } catch (ThrowDemo e) { //方法test01中会抛出异常,因此调用该方法的时候就try catch它预料中的异常 //e.printStackTrace(); //ThrowDemo e = new ThrowDemo(s),初始化自定义异常,追溯并打印本类中该异常的错误源头 //System.out.println(); System.out.println("step03:接收test01中的抛出throw,匹配是ThrowDemo对象,到达test02 Catch 块"); RuntimeException excption01 = new RuntimeException("test02中runtimeException中的catch块"); excption01.initCause(e); //initCause( throwable cause) 即参数为可抛出异常的对象,ThrowDemo e继承Exception父类,即也属于throwable类 //如果没有.initCause( throwable cause),即没有定义causeby源头异常/起始异常---异常链,printStackTrace的时候就不能打印cause by throw excption01; //抛出异常exception01?? } } public static void main(String[] args) { /* * TODO * test01抛出异常 * test02调用有抛出异常的方法,对该方法进行try异常捕获catch,并且包装成运行时异常,继续抛出 * main方法,调用test02方法,尝试捕获test02的异常 */ ThrowDemoTest t01=new ThrowDemoTest(); try{t01.test02(); }catch(Exception e){ System.out.println("step04:到达main Catch 块,catch接收throw出来的excption01"); e.printStackTrace(); } } }
结果result:
step01:准备运行test01
step02:Reach test01,new ThrowDemo 初始化函数构造器--》ThrowDemo异常对象,并抛出throw e
Here is ThrowDemo(String s)
step03:接收test01中的抛出throw,匹配是ThrowDemo对象,到达test02 Catch 块
step04:到达main Catch 块,catch接收throw出来的excption01
java.lang.RuntimeException: test02中runtimeException中的catch块
at com.imooc.season3.ThrowDemoTest.test02(ThrowDemoTest.java:18)
at com.imooc.season3.ThrowDemoTest.main(ThrowDemoTest.java:32)
Caused by: com.imooc.season3.ThrowDemo: test01抛出异常
at com.imooc.season3.ThrowDemoTest.test01(ThrowDemoTest.java:7)
at com.imooc.season3.ThrowDemoTest.test02(ThrowDemoTest.java:13)
... 1 more
并不能看懂,逻辑不是很清楚
异常在哪里?
谢谢啦