从
docs
:
try with resources语句中声明的资源是
Buffered阅读器。声明语句出现在括号内
紧随try关键字之后。Java中的BufferedReader类
SE 7及更高版本实现了java.lang.AutoCloseable接口。
因为BufferedReader实例是在使用资源的try中声明的
语句,无论try语句是否正确,它都将被关闭
正常或突然完成(由于该方法
BufferedReader.readLine抛出IOException)。
基本上,它相当于:
BufferedReader br = new BufferedReader(new FileReader(System.in));
try {
int i = Integer.parseInt(br.readLine());
System.out.println(i);
} finally {
br.close();
}
让我们尝试一下(从这里开始一个工作示例):
public class ClassThatAutoCloses implements java.lang.AutoCloseable {
public ClassThatAutoCloses() {}
public void doSomething() {
System.out.println("Pippo!");
}
@Override
public void close() throws Exception {
throw new Exception("I wasn't supposed to fail");
}
}
public class Playground {
public static void main(String[] args) {
try {
try(var v = new ClassThatAutoCloses() ){
v.doSomething();
}
} catch (Exception e) {
System.err.println("close failed");
e.printStackTrace();
}
}
}
//the output
Pippo!
close failed
java.lang.Exception: I wasn't supposed to fail
at ClassThatAutoCloses.close(ClassThatAutoCloses.java:26)
at Playground.main(Playground.java:24)