Reputation: 1111
I am trying to find out what is the best approach for try/catch when dealing with connections in JDBC.
My personal view is.
Connection conn = null;
try{
conn = getDBConnection();
//Some jdbc code
} catch(SQLException e) {
//...
} finally {
if(conn != null) {
try {
conn.close();
} catch(SQLException e) {
//....
}
}
}
But I have seen few smart guys doing this
Connection conn = null;
try{
conn = getDBConnection();
//Some jdbc code
conn.close();
conn = null;
} catch(SQLException e) {
//...
} finally {
if(conn != null) {
try {
conn.close();
} catch(SQLException e) {
//....
}
}
}
Is there any advantage in closing the connection in try and setting it to null?
Upvotes: 2
Views: 154
Reputation:
Your smart guys are not that smart. Your approach is the way to go. Close the connection only once in your finally
block, and there's no reason to set the connection to null
, that's what automatic garbage collection is for.
Upvotes: 5