还可以在 Java try-with-resources 块中添加 finally 块。它的行为与标准的 finally 代码块无异,这意味着它将作为退出 try-with-resources 代码块前的最后一步被执行,即在任何 catch 代码块被执行后。
如果在 try-with-resources 结构的 finally 代码块中抛出异常,所有之前抛出的异常都将丢失。例如:
package com.hxstrive.jdk7.try_with_resources;
import java.util.Arrays;
/**
* JDK7 新特性 try-with-resources
* @author hxstrive.com
*/
public class TryWithResourcesDemo11 {
static class MyResource implements AutoCloseable {
@Override
public void close() throws Exception {
throw new Exception("MyResource.close error");
}
public void doSomething(String message) {
System.out.println("doSomething() message=" + message.toUpperCase());
}
}
public static void main(String[] args) {
try (MyResource resource = new MyResource()) {
resource.doSomething("hello");
} catch (Exception e) {
System.out.println(Arrays.toString(e.getSuppressed()));
throw new RuntimeException(e);
} finally {
throw new RuntimeException("finally");
}
//结果:
//doSomething() message=HELLO
//[]
//Exception in thread "main" java.lang.RuntimeException: finally
}
}请注意,从 catch 代码块中抛出的异常将被忽略,因为从 finally 代码块中抛出了新的异常。如果没有 catch 代码块,情况也是如此。那么从 try 代码块内部抛出的任何异常都会丢失,因为从 finally 代码块内部抛出了新的异常。之前的任何异常都不会被抑制,因此在 finally 代码块抛出的异常中也不会出现这些异常。