跳到主要内容

Java 捕获多个异常

提示
  1. 多异常捕获:Java 7 之前,需要为不同异常类型编写多个 catch 块,但现在可以在一个 catch 块中捕获多种类型的异常。
  2. 使用竖线分隔:多异常捕获时,不同异常类型间用竖线 | 分隔,并在单个 catch 块中处理。
  3. 基础异常捕获规则:可以只捕获基础异常类(如 Exception),但不能在同一个 catch 块中同时捕获基础和子类异常,以避免编译错误。

在 Java 7 之前,即使存在代码冗余,我们也必须为不同类型的异常编写多个异常处理代码。

让我们看一个例子。

示例 1:多个 catch 块

class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}

输出

/ by zero

在这个例子中,可能会发生两个异常:

  • ArithmeticException,因为我们尝试将一个数除以 0。
  • ArrayIndexOutOfBoundsException,因为我们声明了一个整数数组,数组界限为 0 到 9,我们尝试将值分配给索引 10。

我们在两个 catch 块中都打印出异常消息,即重复代码。

赋值运算符 = 的关联性是从右到左,因此首先抛出带有消息 / by zero 的 ArithmeticException

在一个 catch 块中处理多个异常

在 Java SE 7 及以后版本中,我们现在可以在单个 catch 块中捕获多种类型的异常。

可以由 catch 块处理的每种异常类型都用竖线或管道 | 分隔。

其语法是:

try {
// 代码
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch 块
}

示例 2:多捕获块

class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}

输出

/ by zero

在单个 catch 块中捕获多个异常可以减少代码重复并提高效率。

编译此程序生成的字节码将比具有多个 catch 块的程序小,因为没有代码冗余。

注意: 如果一个 catch 块处理多个异常,那么捕获参数隐式地是 final 的。这意味着我们不能对捕获参数赋值。

捕获基础异常

在单个 catch 块中捕获多个异常时,规则是从一般到专门化。

这意味着如果 catch 块中存在异常的层次结构,我们可以只捕获基础异常,而不是捕获多个专门化的异常。

让我们看一个例子。

示例 3:仅捕获基础异常类

class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

输出

/ by zero

我们知道所有的异常类都是 Exception 类的子类。所以,我们可以简单地捕获 Exception 类,而不是捕获多个专门化的异常。

如果基础异常类已经在 catch 块中指定,不要在同一个 catch 块中使用子异常类。否则,我们将得到一个编译错误。

让我们看一个例子。

示例 4:捕获基础和子异常类

class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (Exception | ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}

输出

Main.java:6: error: 多重捕获语句中的选项不能通过子类化来关联

在这个例子中,ArithmeticExceptionArrayIndexOutOfBoundsException 都是 Exception 类的子类。因此,我们得到了一个编译错误。