Article:
  Best Practices for Exception Handling
Subject:   Correction of the try/finally code
Date:   2006-11-16 15:34:08
From:   rillig
In the article, there is the following code:



Connection conn = null;
try {
conn = getConnection();
... some code that throws SQLException
} finally {
DBUtil.closeConnection(conn);
}


This code is wrong because it could call closeConnection() with a null pointer. The right way to do this is:



final Connection conn = getConnection();
try {
... some code that throws SQLException
} finally {
DBUtil.closeConnection(conn);
}


It's not only shorter, it also takes care that the conn variable does not get overwritten.


Roland

Main Topics Oldest First

Showing messages 1 through 1 of 1.

  • Correction of the try/finally code
    2008-01-21 01:00:38  venkataramanam [View]

    Roland, Well there is a problem with modified code as well. The intention of the author was "getConnection() throws an SQLException". And you have placed the call outside of try/catch. I would say, finally block should for non-nullness of connection variable 'conn' and then only close the connection.