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);
}
}
}
异常的多次捕获与处理
最新推荐文章于 2022-07-13 10:20:16 发布