2

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?

Puru--
  • 1,111
  • 12
  • 27
  • 3
    Your approach is better, also, if you're using java 7, see my answer on try-catch [here](http://stackoverflow.com/questions/17739362/java7-try-with-resources-statement-advantage/17739460#17739460) – morgano Mar 18 '14 at 23:45
  • morgano thanks for pointing this out I am aware of Java 7's cool feature however we are still using JDK6 – Puru-- Mar 18 '14 at 23:50

1 Answers1

5

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.

AxiomaticNexus
  • 6,190
  • 3
  • 41
  • 61
  • I think the smart guys were worried about the fact that, if they don't set `conn` to null, condition check in the finally might succeed cause a exception since the connection is already closed. Thanks!! – Puru-- Mar 18 '14 at 23:56