How to Correctly Close Resources

前端 未结 6 1436
孤独总比滥情好
孤独总比滥情好 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:31

    You can wrap one block into another block:

    try{
      Connection c = ...
        try{
          statement = c.prepareStatement(...);
          try{
            rs = statement.execute(...);
          }finally{
            rs.close();
          }
        }finally{
          statement.close()
        }
      }finally{
        c.close();
      }
    }catch(SQLException e){}
    

    Use the lowermost catch-block for everything that might crop up

提交回复
热议问题