异常的多次捕获与处理

package cn.dali2.code19;

import java.util.ArrayList;

/*异常与处理:
 *           1.多个异常多次捕获,多次处理
 *           2.多个异常一次捕获,多次处理
 *           3.多个异常一次捕获,一次处理
 *注意:
 *      当多个异常一次捕获,多次处理的时候,当我们在try中抛出异常的时候,
 *      这个异常对象会从上到下对catch进行检测,检测他的参数列表中的异常对象与我们抛出的对象是否类型一样
 *      或者有父子类关系。如果一样或者是父子类,则会赋值。否则会造成多态的问题,本来是父类的异常对象,子类对象却进去了。
 *      这样的话,该子类对应的catch并没有使用到,这样会报错。
 *      所以,多次处理写catch的时候,如果有父子类关系,子类写在前面,父类写在后面
 *      */
public class Demo04 {
    public static void main(String[] args) {
        int[] arrayA = new int[2];
        ArrayList<Integer> list01 = new ArrayList<>();
        //多次捕获,多次处理
        try {
            System.out.println(arrayA[3]);//ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e);
        }

        try {
            System.out.println(list01.get(4));//IndexOutOfBoundsException
        } catch (IndexOutOfBoundsException e) {
            System.out.println(e);
        }
        System.out.println("=========================================");
        //一次捕获,多次处理
        try{
            System.out.println(list01.get(4));//IndexOutOfBoundsException
            System.out.println(arrayA[3]);//ArrayIndexOutOfBoundsException
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println(e);
        }catch(IndexOutOfBoundsException e){
            System.out.println(e);
        }
        System.out.println("=========================================");
        //一次捕获,一次处理
        try{
            System.out.println(list01.get(4));//IndexOutOfBoundsException
            System.out.println(arrayA[3]);//ArrayIndexOutOfBoundsException
        }catch(Exception e){
            System.out.println(e);
        }

    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值