【发布时间】:2014-12-21 02:34:20
【问题描述】:
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 块中抛出。
【问题讨论】:
-
为什么不应该呢?你是老板。你决定做什么,即使它是愚蠢的。
-
IOException 扩展异常
-
编译器不知道永远不会抛出 IOException。你也没有。
标签: java exception exception-handling try-with-resources