我正在阅读有关JDK7中的try-with-resource的内容,当我考虑将我的应用程序升级为使用JDK7运行时,我遇到了这个问题.
当使用BufferedReader时,例如写入抛出IOException和close抛出IOException ..在catch块中我关注写入引发的IOException ..但我不会太在意关闭抛出的那个..
数据库连接和任何其他资源的问题相同..
作为一个例子,我创建了一个自动关闭资源:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
现在使用它时:
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何在不必为BufferedReader等类创建包装器的情况下区分这些异常?
大多数情况下,我将资源关闭在finally块中的try/catch中,而不关心处理它.