74、多异常处理

一、多异常处理,方式:
    1、多个异常,分别处理
    2、多个异常一次捕获,多次处理。
        注意:在此情况下,如果多个异常有子父类关系,子类必须放前,否则会报错
    3、多个异常,一次捕获,一次处理
二、说明:运行时的异常,可以不抛出也可以不处理,虚拟机会处理

三、举例

import java.util.ArrayList;

public class Demo06ExceptionMul {
    public static void main(String[] args) {
        int[] iarray = new int[]{1,2,3};
        ArrayList<Integer> array = new ArrayList<>();

        //多次捕获,多次处理
        System.out.println("多次捕获,多次处理");
        try{
            System.out.println(iarray[3]);
        }catch (ArrayIndexOutOfBoundsException e)
        {
            System.out.println(e);
        }

        try{
            System.out.println(array.get(3));
        }catch (IndexOutOfBoundsException e)
        {
            System.out.println(e);
        }

        //一次捕获,多次处理
        System.out.println("一次捕获多次处理");
        /*由于ArrayIndexOutOfBoundsException 是IndexOutOfBoundsException的子类,因此要放前面*/
        try{
            System.out.println(iarray[3]);
            //System.out.println(array.get(3));

        }catch (ArrayIndexOutOfBoundsException e)
        {
            System.out.println(e);
        }catch (IndexOutOfBoundsException e)
        {
            System.out.println(e);
        }

        //一次捕获一次处理
        System.out.println("一次捕获一次处理");
        try{
            System.out.println(iarray[3]);
            System.out.println(array.get(3));
        }catch (Exception e)
        {
            System.out.println(e);
        }
        System.out.println("程序结束!");
    }
}

输出:

多次捕获,多次处理
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 0
一次捕获多次处理
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
一次捕获一次处理
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
程序结束!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值