一段代码中,有多个异常需要处理,我们有这几种方式进行
1.多个异常分别处理。
我写了一段代码,供大家与我进行理解,如下:
public class Test {
public static void main(String[] args) {
try {
int arr[]={1,2,3};
System.out.println(arr[3]);
}catch (ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
就是一个异常,就去写一个try catch,用来处理异常
2.多个异常一次捕获,多次处理。
与之相应的,我也写了一串代码,如下:
public class Test {
public static void main(String[] args) {
try {
int arr[]={1,2,3};
System.out.println(arr[3]);
int a = 0;
int b=3;
System.out.println(b/a);
}catch (ArrayIndexOutOfBoundsException e){
System.out.println(e);
}catch ( Exception b){
System.out.println("111");
}
}
首先会抛出第一个异常处理的结果,也就是会抛出超出数组索引长度的异常,我将第一个异常注释掉了之后,会抛出第二个异常,也就是打印了11。
一个try多个catch有注意事项:catch里面定义的异常变量,如果有父子关系,那么子类的异常变量必须写在上面,否则就会报错
3.多个异常一次捕获一次处理。
把try的异常全交给一个catch来处理,但是catch中所定义的变量,必须是try中的父类对象。
我也相应的做出了一个代码展示,如下:
try {
int arr[]={1,2,3};
System.out.println(arr[3]);
int a = 0;
int b=3;
System.out.println(b/a);
}catch ( Exception b){
System.out.println("111");
}