我正在阅读有关 JDK7 中的 try-with-resource 的信息,当我考虑升级我的应用程序以使用 JDK7 运行时,我遇到了这个问题。
例如,当使用 BufferedReader 时,write 抛出 IOException 并且 close 抛出 IOException .. 在 catch 块中,我担心 write 抛出的 IOException .. 但我不太关心 close 抛出的那个 ..
数据库连接也有同样的问题..和任何其他资源..
例如,我创建了一个可自动关闭的资源:
public class AutoCloseableExample implements AutoCloseable {
public AutoCloseableExample() throws IOException{
throw new IOException();
}
@Override
public void close() throws IOException {
throw new IOException("An Exception During Close");
}
}
现在使用它时:
public class AutoCloseTest {
public static void main(String[] args) throws Exception {
try (AutoCloseableExample example = new AutoCloseableExample()) {
System.out.println(example);
throw new IOException("An Exception During Read");
} catch (Exception x) {
System.out.println(x.getMessage());
}
}
}
如何在不必为诸如 BufferedReader 之类的类创建包装器的情况下区分此类异常?
大多数情况下,我将资源关闭在 finally 块内的 try/catch 中,而不关心如何处理它。