1.介绍
JDK1.7之后可以在一个catch语句中捕获多个异常,通过"或"运算符"|"列出需要捕获的多个异常。当对多个种类的异常有相同的处理时,这种写法能是得代码简洁易读。
但是需要注意的是,这多个异常的级别需要相同,不能是继承的关系。
2.举例
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
int c = a / b;
} catch (ArithmeticException | NullPointerException e) {
System.out.println(e.getClass());
System.out.println("Catch it!");
}
}输出的结果:
class java.lang.ArithmeticException
Catch it!
3.注意捕获的多个异常的级别要相同,否则会编译报错
报错样例:
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
int c = a / b;
// 类ArithmeticException 继承 类RuntimeException,所以不能放在一个catch中
// 会编译报错
} catch (ArithmeticException | RuntimeException e) {
System.out.println(e.getClass());
System.out.println("Catch it!");
}
}
IDE提示报错:

















