资源试一试的目的是什么? [英] What's the purpose of try-with-resources statements?

查看:73
本文介绍了资源试一试的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 7具有称为

Java 7 has a new feature called try-with-resources. What is it? Why and where we should use it and where we can take advantage of this feature?

try语句没有catch块,这使我感到困惑.

The try statement has no catch block which confuses me.

推荐答案

之所以引入它,是因为Java中使用的某些资源(例如SQL连接或流)难以正确处理.例如,在Java 6中,要正确处理 InputStream ,您必须执行以下操作:

It was introduced because of some resources used in Java (like SQL connections or streams) being difficult to be handled properly; as an example, in java 6 to handle a InputStream properly you had to do something like:

InputStream stream = new MyInputStream(...);
try {
    // ... use stream
} catch(IOException e) {
   // handle exception
} finally {
    try {
        if(stream != null) {
            stream.close();
        }
    } catch(IOException e) {
        // handle yet another possible exception
    }
}

您是否注意到丑陋的两次尝试?现在使用try-with-resources,您可以执行以下操作:

Do you notice that ugly double try? now with try-with-resources you can do this:

try (InputStream stream = new MyInputStream(...)){
    // ... use stream
} catch(IOException e) {
   // handle exception
}

close()被自动调用,如果抛出IOException,它将被禁止(如

and close() is automatically called, if it throws an IOException, it will be supressed (as specified in the Java Language Specification 14.20.3) . Same happens for java.sql.Connection

这篇关于资源试一试的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆