How to Correctly Close Resources

前端 未结 6 1433
孤独总比滥情好
孤独总比滥情好 2020-12-09 16:48

As I was cleaning up some code, FindBugs pointed me to a bit of JDBC code that uses Connection, CallableStatement, and ResultSet objects. Here\'s a snippet from that code:

6条回答
  •  抹茶落季
    2020-12-09 17:26

    Use Lombok's cleanup, if you can:

    @Cleanup
    Connection c = ...
    @Cleanup
    statement = c.prepareStatement(...);
    @Cleanup
    rs = statement.execute(...);
    

    This works translates to three nested try-finally blocks and works fine with exception. Never ever swallow an exception without a very good reason!

    An alternative:

    Write an own utility method like this:

    public static void close(ResultSet rs, Statement stmt, Connection con) throws SQLException {
        try {
            try {
                if (rs!=null) rs.close();
            } finally {
                if (stmt!=null) stmt.close();
            }
        } finally {
            if (con!=null) con.close();
        }
    }
    

    and use it in

    try {
        Connection con = ...
        Statement stmt = ...
        ResultSet rs = ...
    } finally {
        close(rs, stmt, con);
    }
    

    and let the Exception bubble up or handle it as you want.

提交回复
热议问题