Java基础:异常捕获顺序

来源:互联网 发布:天猫双十一销售额数据 编辑:程序博客网 时间:2024/06/05 20:57

 转载请注明出处:jiq•钦's technical Blog 


public voidtestException(){int a[] = {1,2,3};int q = 0;try{for(int i=0;i<a.length;i++){a[i] /= q;}}catch(ArithmeticException h){System.out.print("ArithmeticException\n");        //执行}catch(Exception e){System.out.print("Exception\n");        //不会执行,且必须放在ArithmeticException后面/** * 范围更大的Exception不但必须放在后面 * 而且放在后面还不会被执行(被前面的范围更小的 * 异常拦截了),那这样还有什意义呢??? */}finally{System.out.print("finally\n");}}//<span style="color:#3333ff;">output</span>ArithmeticExceptionfinally

 *        要点1虽然ArithmeticException继承自Exception,但是当发生ArithmeticException异常

 *                        并捕获的时候,就只会捕获实际发生的这个异常,并不会因为Exception是其父类而

 *                        执行Exception那个catch子句。

 *        要点2但是如果你尝试将范围更大的Exceptioncatch语句放到的catch语句的前面,那么就会发生

 *                        catch子句不可到达的错误“Unreachablecatch block for ArithmeticException.

 *                        Itis already handled by the catch block for Exception

 *                        即范围更大的异常(父类)必须放在后面,如果没有继承关系,比如ClassNotFoundException

 *                        ArithmeticExceptioncatch子句之间就无所谓先后关系。

1 0
原创粉丝点击