Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why JDBC connections needs to close in finally block?

Tags:

java

jdbc

Connection conn = null;
Statement stmt = null; 
ResultSet rs = null;
try
{
    conn = geting the connection object ( using DriverManager.getConnection() method or using connection pool)
    stmt = conn.createStatement ("select ...");
   // some other logic here
}
catch (SQLException e)
{
    // handling the exceptions
}
finally
{

}

Here my question is while closing the connection object in the following cases what are the problems it will come.

  1. Assume if there is no exception occurred, in try block there it self closing the connection object.

    try {
         // same above code 
         stmt.close();
         conn.close();
    } catch(Exception ex) {
        // handling the exceptions
    } finally {
    
    }
    
  2. If some exception is occured so it will goes to catch block, there it self closing the connection object.

    try {
         // same above code 
    
    } catch(Exception ex) {
        // handling the exceptions
        stmt.close();
        conn.close();
    } finally {
    
    }
    
  3. Closing the connection object in finally block.

    try {
         // same above code 
    
    } catch(Exception ex) {
        // handling the exceptions
    
    } finally {
        stmt.close();
        conn.close();
    } 
    
  4. Difference between closing the connection object using close() method and closing the pooled connection using close().

Note: Please don't say closing the connection object in finally block is good. I know that one. If i keep the close connection in try block, catch block is there any problems please explain.

like image 986
Ranga Reddy Avatar asked Sep 28 '15 06:09

Ranga Reddy


1 Answers

It is recommended to close the connection in the finally block because if you have multiple catch blocks (as you should: you should never catch generic Exception) you will not have to re-write the closing statements.

A finally block will always be executed after a try, no matter what happens. So if you get a NullPointerException, or some other exception you didn't handle, with the finally block you will be sure that your resources are closed properly.

But if you are on java 7, I'd suggest to use the try-with-resources block

like image 181
BackSlash Avatar answered Oct 06 '22 01:10

BackSlash