【发布时间】:2014-01-06 14:34:27
【问题描述】:
我正在阅读有关 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 中,而不关心如何处理它。
【问题讨论】:
-
我说的是整体概念..反正..我现在加个代码sn-p..
标签: java java-7 try-with-resources