从 Java 7 开始,我们可以使用 try-with-resources 语句:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
ifbr.readLine()
和br.close()
both throw exceptions ,都会readFirstLineFromFile
从try块中抛出异常( 的异常),并且try-with-resources 语句的隐式 finally 块中的异常( 的异常)将被抑制。br.readLine()
br.close()
在这种情况下,我们可以通过从try 块的异常中调用方法来从隐式 finally 块中检索被抑制的异常,如下所示:getSuppresed
try {
readFirstLineFromFile("Some path here..."); // this is the method using try-with-resources statement
} catch (IOException e) { // this is the exception from the try block
Throwable[] suppressed = e.getSuppressed();
for (Throwable t : suppressed) {
// Check t's type and decide on action to be taken
}
}
但是假设我们必须使用使用比 Java 7 更旧的版本编写的方法,其中使用了 finally 块:
static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
那么如果br.readLine()
再br.close()
一次都抛出异常,情况就会逆转。该方法readFirstLineFromFileWithFinallyBlock
将抛出finally 块的异常(的异常br.close()
),而try 块的异常(的异常br.readLine()
)将被抑制。
所以我的问题是:在第二种情况下,我们如何从try 块中检索被抑制的异常?
来源:http ://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html