使用try-with-resources静态关闭资源 [英] Close resource quietly using try-with-resources
问题描述
可以忽略使用try-with-resources语句关闭资源时抛出的异常吗?
Is it possible to ignore the exception thrown when a resource is closed using a try-with-resources statement?
示例:
class MyResource implements AutoCloseable{
@Override
public void close() throws Exception {
throw new Exception("Could not close");
}
public void read() throws Exception{
}
}
//this method prints an exception "Could not close"
//I want to ignore it
public static void test(){
try(MyResource r = new MyResource()){
r.read();
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
或者我应该继续关闭一个终于
Or should I continue to close in a finally
instead?
public static void test2(){
MyResource r = null;
try {
r.read();
}
finally{
if(r!=null){
try {
r.close();
} catch (Exception ignore) {
}
}
}
}
推荐答案
我在coin-dev邮件列表中找到了这个答案:
http://mail.openjdk.java.net/pipermail/coin-dev/2009-April/001503.html
I found this answered on the coin-dev mailing list: http://mail.openjdk.java.net/pipermail/coin-dev/2009-April/001503.html
5。关闭方法的一些失败可以被安全地忽略(例如,
关闭一个打开以供读取的文件)。这个结构是否提供
?
否。虽然这个功能似乎有吸引力,但不清楚的是,
值得增加复杂性。实际上,这些无害的
例外很少发生,所以如果这些例外被忽略,程序将不再是稳健的
。如果你觉得你必须忽略它们,
有一个解决方法,但它不漂亮:
No. While this functionality seems attractive, it is not clear that it's worth the added complexity. As a practical matter these "harmless exceptions" rarely if ever occur, so a program will be no more robust if these exceptions are ignored. If you feel you must ignore them, there is a workaround, but it isn't pretty:
static void copy(String src, String dest) throws IOException {
boolean done = false;
try (InputStream in = new FileInputStream(src)) {
try(OutputStream out = new FileOutputStream(dest)) {
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
}
done = true;
} catch(IOException e) {
if (!done)
throw e;
}
}
这篇关于使用try-with-resources静态关闭资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!