57

我对 try-with-resources 有疑问,我只是想确定一下。如果我需要对异常做出反应,并且我仍然需要 catch 块中的资源,我可以使用它吗?给出的例子是这样的:

try (java.sql.Connection con = createConnection())
{
    con.setAutoCommit(false);
    Statement stm = con.createStatement();
    stm.execute(someQuery); // causes SQLException
}
catch(SQLException ex)
{
    con.rollback();
    // do other stuff
}

我担心在这种情况下我仍然注定要使用旧的 try-catch-finally,即使根据 oracle 文档 - “catch and finally blocks in a try-with-resources statement, any catch or finally block are run after the resources宣布已关闭。”

4

4 回答 4

59

根据语言规范,将在执行 catch 子句之前关闭连接(http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.3.2) .

一个可能的解决方案是嵌套 try-with-resources 语句:

try (java.sql.Connection con = createConnection())
{
    con.setAutoCommit(false);
    try (Statement stm = con.createStatement())
    {
        stm.execute(someQuery); // causes SQLException
    }
    catch(SQLException ex)
    {
        con.rollback();
        con.setAutoCommit(true);
        throw ex;
    }
    con.commit();
    con.setAutoCommit(true);
}

希望这能说明这一点。如果您打算在生产代码中使用它,这应该会有所改进。

例如,如果您正在使用连接池,那么您必须在获得连接时返回连接,因此 con.setAutoCommit(true); 应该在 finally 子句中完成。这意味着外部的 try-with-resources 应该是传统的 try-catch-finally。

编辑 (2018)

我仍然看到人们对此发表评论,所以我想我会给它一个 2018 年的回复。我不再使用Java了,主要是使用Scala、Clojure和Kotlin,并且这段代码没有经过测试,所以请把这当作另一个例子。但是,由于 Java 有 lambda,我认为以下方法要好得多。我在这些其他语言的生产代码中做了类似的事情。

在这种方法中,有一个 inTransaction 函数来处理所有讨厌的事务。但是用法很简单。

public class Foo {

    interface ConnectionProvider {
        Connection get() throws SQLException;
    }

    public static <A> A doInTransation(ConnectionProvider connectionProvider, Function<Connection, A> f) throws SQLException {
        Connection connection = null;
        A returnValue;
        boolean initialAutocommit = false;
        try {
            connection = connectionProvider.get();
            initialAutocommit = connection.getAutoCommit();
            connection.setAutoCommit(false);
            returnValue = f.apply(connection);
            connection.commit();
            return returnValue;
        } catch (Throwable throwable) {
            // You may not want to handle all throwables, but you should with most, e.g.
            // Scala has examples: https://github.com/scala/scala/blob/v2.9.3/src/library/scala/util/control/NonFatal.scala#L1
            if (connection != null) {
                connection.rollback();
            }
            throw throwable;
        } finally {
            if (connection != null) {
                try {
                    if(initialAutocommit){
                        connection.setAutoCommit(true);
                    }
                    connection.close();
                } catch (Throwable e) {
                    // Use your own logger here. And again, maybe not catch throwable,
                    // but then again, you should never throw from a finally ;)
                    StringWriter out = new StringWriter();
                    e.printStackTrace(new PrintWriter(out));
                    System.err.println("Could not close connection " + out.toString());
                }
            }
        }
    }

    public static void main(String[] args) throws SQLException {
        DataSource ds = null;

        // Usage example:
        doInTransation(ds::getConnection, (Connection c) -> {
            // Do whatever you want in a transaction
            return 1;
        });
    }
}

我希望有一些经过实战考验的库可以为您做这些事情,至少在这些其他语言中是这样。

我看到有一些关于自动提交和连接池的评论。上面的例子应该不知道连接来自哪里,一个池与否,即只有当它是初始值时才将它设置回true。因此,如果从池中它是错误的,则不应触摸它。

关于资源尝试的最后一句话。我不认为这是一个很好的抽象,所以我会在更复杂的场景中小心使用它。

于 2013-04-08T15:55:26.823 回答
22

在您的代码中,您正在捕获“SQLException”以执行 autoCommit 重置。任何类型的运行时异常(如空指针异常)都会从您的代码中冒泡,而无需重置自动提交。

try-with-resource 语法使编译器生成一些精彩的代码来覆盖所有执行路径,并通过关闭来跟上所有被抑制的异常。使用几个帮助类,您可以将提交/回滚和重置自动提交插入代码生成过程:

import java.sql.SQLException;
import java.sql.Connection;

public class AutoRollback implements AutoCloseable {

    private Connection conn;
    private boolean committed;

    public AutoRollback(Connection conn) throws SQLException {
        this.conn = conn;        
    }

    public void commit() throws SQLException {
        conn.commit();
        committed = true;
    }

    @Override
    public void close() throws SQLException {
        if(!committed) {
            conn.rollback();
        }
    }

}

public class AutoSetAutoCommit implements AutoCloseable {

    private Connection conn;
    private boolean originalAutoCommit;

    public AutoSetAutoCommit(Connection conn, boolean autoCommit) throws SQLException {
        this.conn = conn;
        originalAutoCommit = conn.getAutoCommit();
        conn.setAutoCommit(autoCommit);
    }

    @Override
    public void close() throws SQLException {
        conn.setAutoCommit(originalAutoCommit);
    }

}

现在您可以使用“try with resource”语法来控制回滚和自动提交,如下所示:

    try(Connection conn = getConnection(),
        AutoSetAutoCommit a = new AutoSetAutoCommit(conn,false),
        AutoRollback tm = new AutoRollback(conn)) 
    {

        // Do stuff

        tm.commit();
    } 
于 2016-05-09T18:17:53.080 回答
9
    //try with resources
    try(Connection conn = this.connectionProvider.getConnection()){//auto close BEFORE reach this , catch block, so we need a inner try block for statement
        boolean oldAutoCommit=conn.getAutoCommit();
        conn.setAutoCommit(false);//auto commit to false
        try(
            Statement stm = con.createStatement()
        ){
            stm.execute(someQuery); // causes SQLException
            conn.commit();//commit
        }
        catch (SQLException ex){
            conn.rollback();//error, rollback
            throw ex;//If you need to throw the exception to the caller
        }
        finally {
            conn.setAutoCommit(oldAutoCommit);//reset auto commit
        }
    }
于 2015-05-08T04:56:09.230 回答
5

在上面的例子中,我认为最好放在con.commit()nested 里面try-catch,因为它也可以 throw SQLException

 try (java.sql.Connection con = createConnection())
    {
        con.setAutoCommit(false);
        try (Statement stm = con.createStatement())
        {
            stm.execute(someQuery); // causes SQLException
            con.commit();           // also causes SQLException!
        }
        catch(SQLException ex)
        {
            con.rollback();
            throw ex;
        }finally{
            con.setAutoCommit(true);
        }
    }

我们在生产环境中遇到了这样的问题,会话未关闭。

于 2014-04-30T16:42:31.070 回答