try-with-resources 语句的目的是什么? [英] What's the purpose of try-with-resources statements?

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

问题描述

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,它将被抑制(如 Java 语言规范 14.20.3).java.sql.Connection

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

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

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