一段代码可能会生成多个异常
当引发异常时,会按顺序来查看每个 catch 语句,并执行第一个类型与异常类型匹配的语句
执行其中的一条 catch 语句之后,其他的 catch 语句将被忽略
try{
…….
} catch(ArrayIndexOutOfBoundsException e) {
……
} catch(Exception e) {
……
}
使用多重 catch 语句时,异常子类一定要位于异常父类之前
try{
…...
} catch(Exception e) {
……
} catch(ArrayIndexOutOfBoundsException e) { //错的写法
……
}
实例:
class ExceptionCode {
/**构造方法.*/
protected ExceptionCode() {
}
/**这个方法将将零作除数.*/
public void calculate() {
try {
int num = 0;
int num1 = 42 / num;
}catch (Exception e) {
System.out.println("父类异常 catch 子句");
}catch (ArithmeticException ae) {
// 错误 – 不能到达的代码
System.out.println("这个子类的父类是"
+ "exception 类,且不能到达");
}
}
}
class UnreachableCode {
/**构造方法.*/
protected UnreachableCode() {
}
/**
* 类和应用程序的唯一进入点.
* @param args 字符串参数的数组
*/
public static void main(String[] args) {
ExceptionCode obj = new ExceptionCode();
obj.calculate();
}
}



