Java 多重异常
多重异常
有时,同一个 try 代码块中可能会出现不同的错误(异常)。
您可以使用多个 catch 代码块来处理它们。
一个 try 代码块,多个 catch 代码块
您可以添加多个 catch 代码块,Java 将运行第一个与抛出的异常类型匹配的 catch 代码块:
示例
public class Main {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[10]); // ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index does not exist.");
}
catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
catch (Exception e) {
System.out.println("Something else went wrong.");
}
}
}
结果:
Array index does not exist.
说明: 只会抛出第一个异常(ArrayIndexOutOfBoundsException),因此只会执行第一个匹配的 catch 语句。
顺序很重要
你应该始终将更具体的异常放在前面,更一般的异常放在后面。否则,一般的 catch 语句会捕获到错误,而具体的异常永远不会执行。
Example (bad order)
try {
int result = 10 / 0;
}
catch (Exception e) {
System.out.println("General error.");
}
catch (ArithmeticException e) {
// 这永远无法实现。
System.out.println("Divide by zero.");
}
提示:始终将Exception(通用异常)放在末尾。
多重捕获
从 Java 7 开始,您可以使用 | 符号在一个 catch 代码块中捕获多个异常。当需要以相同的方式处理不同的异常时,此功能非常有用,这样您就不必重复编写代码。
示例
try {
int result = 10 / 0;
int[] numbers = {1, 2, 3};
System.out.println(numbers[10]);
}
catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("Math error or array error occurred.");
}

