资源在 catch 或 finally 阻塞之前关闭。请参阅本教程。
try-with-resources 语句可以像普通的 try 语句一样有 catch 和 finally 块。在 try-with-resources 语句中,任何 catch 或 finally 块都会在声明的资源关闭后运行。
评估这是一个示例代码:
class ClosableDummy implements Closeable {
public void close() {
System.out.println("closing");
}
}
public class ClosableDemo {
public static void main(String[] args) {
try (ClosableDummy closableDummy = new ClosableDummy()) {
System.out.println("try exit");
throw new Exception();
} catch (Exception ex) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
}
}
输出:
try exit
closing
catch
finally