How to Correctly Close Resources

前端 未结 6 1430
孤独总比滥情好
孤独总比滥情好 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条回答
  •  -上瘾入骨i
    2020-12-09 17:28

    Well basically that is what you do except you first of all don't necessarily swallow the exception (you can null check and at least LOG the exception). Second, you can set up a nice utility class with things like

    public static void close(ResultSet rs) {
       try { if (rs != null) rs.close();
       } catch (SQLException (e) {
          log.error("",e);
       } 
    
    }
    

    Then you just static import that class.

    your finally becomes something like

    finally {
         close(resultset);
         close(statement);
         close(connection);
    }
    

    which really isn't that hideous.

提交回复
热议问题