Java基础:异常捕获顺序

 转载于:https://blog.csdn.net/jiyiqinlovexx/article/details/46597899

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>
ArithmeticException
finally

 *        要点1:虽然ArithmeticException继承自Exception,但是当发生ArithmeticException异常
 *                        并捕获的时候,就只会捕获实际发生的这个异常,并不会因为Exception是其父类而

 *                        执行Exception那个catch子句。

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

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

 *                        Itis already handled by the catch block for Exception”

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

 *                        和ArithmeticException的catch子句之间就无所谓先后关系。
 

猜你喜欢

转载自blog.csdn.net/qq_28817739/article/details/85106837