一、异常的捕获
1.1. 多个异常,一次捕获
由于 Exception 类是所有异常类的父类,因此可以用这个类型表示捕捉所有异常。这种写法不推荐,因为编译器会提示有风险但不指明具体风险。
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println("before");
arr = null;
System.out.println(arr[100]);
System.out.println("after");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("after try catch");
}
}

1.2. 异常之间的父子关系
如果异常之间具有父子关系,子类异常必须在父类异常之前被 catch,否则语法错误。例如 NullPointerException 是 RuntimeException 的子类,若先 catch RuntimeException,则第二个 catch 无法到达。
public class Main {
public static void main(String[] args) {
try {
throw new NullPointerException();
} catch (RuntimeException e) {
System.out.println("捕获运行时异常");
e.printStackTrace();
} (NullPointerException e) {
System.out.println();
}
}
}



