public class SampleCloseable implements AutoCloseable {
private String name;
public SampleCloseable(String name){
this.name = name;
}
@Override
public void close() throws Exception {
System.out.println("closing: " + this.name);
}
}
和主要课程
public class Main{
public static void main(String args[]) {
try(SampleCloseable sampleCloseable = new SampleCloseable("test1")){
System.out.println("im in a try block");
} catch (IOException e) {
System.out.println("IOException is never thrown");
} catch (Exception e) {
} finally{
System.out.println("finally");
}
}
}
但是,当我在 SampleCloseable 内的 close() 方法上删除 throws 异常时,我收到一个编译器错误,指出 IOException 永远不会在相应的 try 块中引发。