You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@tomcat.apache.org by anjan bacchu <an...@gmail.com> on 2006/05/17 21:43:56 UTC

Concise way of closing DB resources code sample

Hi All,

  I was looking at the   DataSource HOWTO
page<http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html>and
noticed that the recommended way of closing (BELOW)

finally {
    // Always make sure result sets and statements are closed,
    // and the connection is returned to the pool
    if (rs != null) {
      try { rs.close(); } catch (SQLException e) { ; }
      rs = null;
    }
    if (stmt != null) {
      try { stmt.close(); } catch (SQLException e) { ; }
      stmt = null;
    }
    if (conn != null) {
      try { conn.close(); } catch (SQLException e) { ; }
      conn = null;
    }
 }

can be condensed to

        finally {
            try {
                if (null != rs) {
                    rs.close();
                }
            }
            finally {
                try {
                    if (null != stmt) {
                        stmt.close();
                    }
                }
                finally {
                    if (null != conn) {
                        conn.close();
                    }
                }
            }
        }

This is one (among other) places where it makes sense to use the try/finally
block rather than
the try/catch block.

Just wanted to share this -- if the developers think it makes sense, then
the updated sample would be
useful to all the tomcat users, especially noobs.

Thank you,
<http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html>--

BR,
Anjan Bacchu
Summit Information Systems