多异常处理
A:对代码进行异常检测,并对检测的异常传递给catch处理。对每种异常信息进行不同的捕获处理。
void show(){ //不用throws
try{
throw new Exception();//产生异常,直接捕获处理
}catch(XxxException e){
//处理方式
}catch(YyyException e){
//处理方式
}catch(ZzzException e){
//处理方式
}
}
※注意:这种异常处理方式,要求多个catch中的异常不能相同,并且若catch中的多个异常之间有子父类异常的关系,那么子类异常要求在上面的catch处理,父类异常在下面的catch处理。
package com.itheima_01;
/*
* 如何处理多异常:
* 可以使用多个try...catch语句
* 使用一个try和多个catch
*
* 多个catch之间的顺序
* 多个catch之间可以有子父类
* 平级之间没有顺序关系
* 如果有子父类,父类异常必须放在后面
*/
public class ExceptionDemo2 {
public static void main(String[] args) {
// method();
try {
String s = null;
System.out.println(s.length());
int[] arr = new int[5];
System.out.println(arr[8]);
System.out.println(2 / 0);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("出现数组越界异常");
} catch (NullPointerException e) {
System.out.println("出现空指针异常");
} catch (Exception e) {
System.out.println("出现异常");
}
}
private static void method() {
try {
String s = null;
System.out.println(s.length());
} catch (NullPointerException e) {
System.out.println("出现空指针异常");
}
try {
int[] arr = new int[5];
System.out.println(arr[8]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("出现数组越界异常");
}
}
}