在 Java 7 中,可以在同一个捕获块中捕获多个不同的异常。这也被称为多重捕获。
在 Java 7 之前,您可以这样写
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(SQLException e) {
logger.log(e);
} catch(IOException e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}如您所见,SQLException 和 IOException 这两种异常的处理方式相同,但您仍需为它们编写两个单独的 catch 块。
在 Java 7 中,您可以使用多重捕获语法捕获多个异常:
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(SQLException | IOException e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}请注意第一个 catch 代码块中的两个异常类名是如何被管道符 | 分隔开来的。异常类名之间的管道符就是用同一个 catch 子句声明多个异常的方法。
package com.hxstrive.jdk7.try_with_resources;
import java.io.FileInputStream;
import java.io.IOException;
/**
* JDK7 新特性 try-with-resources
* @author hxstrive.com
*/
public class TryWithResourcesDemo15 {
public static void main(String[] args) {
FileInputStream input = null;
try {
input = new FileInputStream("D:\\test.txt");
int data = -1;
while ((data = input.read()) != -1) {
System.out.print((char) data);
Thread.sleep(50); // 模拟延时,实现打字效果
}
} catch (IOException | InterruptedException e) {
System.out.println("文件IO/中断异常,原因:" + e.getMessage());
} catch (Exception e) {
System.out.println("未知异常,原因:" + e.getMessage());
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}