尝试使用Java 1.6中的资源 [英] Try-with-resources equivalent in Java 1.6

查看:108
本文介绍了尝试使用Java 1.6中的资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

    public class Main {

        public static void main(String[] args) throws SQLException {

            try (
                    Connection conn = DBUtil.getConnection(DBType.HSQLDB);
                    Statement stmt = conn.createStatement(
                            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                    ResultSet rs = stmt.executeQuery("SELECT * FROM tours");
                    ) {

            DBUtil.getConnection();

            } catch (SQLException e) {
                DBUtil.processException(e);
            } 

        }

    }

我使用此代码从数据库中获取数据。我的问题是我不允许使用Java 1.7编译器并且必须使用1.6。
如何将try-with-resources-code转换为与1.6编译器一起使用?
在这个特殊的尝试块中究竟发生了什么?

I use this code to fetch data from a database. My problem is that I'm not allowed to use the Java 1.7 compiler and have to use 1.6. How can I translate the try-with-resources-code to use with a 1.6 compiler? What exactly happens in this special try block?

推荐答案

Oracle解释了如何使用资源尝试这里

Oracle explains how try-with-resources works here

TL; DR它是:

在Java 1.6中没有简单的方法。问题是Exception中没有Suppressed字段。您可以忽略它并硬编码当尝试AND关闭抛出不同异常时发生的事情,或者创建自己的具有被抑制字段的Exception子层次结构。

The TL;DR of it is:
There is no simple way of doing this in Java 1.6. The problem is the absence of the Suppressed field in Exception. You can either ignore that and hardcode what happens when both try AND close throw different exceptions, or create your own Exception sub-hierarchy that has the suppressed field.

在第二个case,上面的链接给出了正确的方法:

In the second case, the link above gives the proper way of doing it:

   AutoClose autoClose = new AutoClose();
   MyException myException = null;
   try {
       autoClose.work();
   } catch (MyException e) {
       myException = e;
       throw e;
   } finally {
       if (myException != null) {
           try {
               autoClose.close();
           } catch (Throwable t) {
               myException.addSuppressed(t);
           }
       } else {
           autoClose.close();
       }
   }  

相当于

try (AutoClose autoClose = new AutoClose()) {
    autoClose.work();
}

如果你想让它变得更容易而不是创造一大堆新东西异常类,你必须决定在finally(t或e)中的catch子句中抛出什么。

In case you want to make it easier and not create a whole lot of new Exception classes, you will have to decide what to throw in the catch clause inside the finally (t or e).

PS。在上面的链接中还讨论了在try中处理多个变量声明。 正确所需的代码量是惊人的。大多数人通过不处理finally块中的异常并使用nullcheck来获取Java 1.6中的快捷方式。

PS. Dealing with multiple variable declaration in the try is also discussed in the link above. And the amount of code that you need to do it properly is staggering. Most people take shortcuts in Java 1.6 by not coping with exceptions in the finally block and using nullchecks.

这篇关于尝试使用Java 1.6中的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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