giozh
giozh

Reputation: 10068

JDBC connection manager and Connection object in case of Exception

I've a jdbc postgresql app and I write the "standard" connection manager. For each successful transaction, I close the statement object, and connection object. If one of SQLException or ClassNotFoundException occours, what happen to statement and connection object? In catch block should I close this two object or not? Something like:

Connection conn = null;
PreparedStatement pstm = null;
try {
    conn = ConnectionManager.getConnection();
    pstm = conn.CreateStatement(statement);
    //set statement
    }catch (SqlException ex) {
        if(conn != null) {
            pstm.close();
            conn.close();
        }
        throw new MyException("error");
    }catch (ClassNotFoundException ex) {
        if(conn != null) {
            pstm.close();
            conn.close();
        }
        throw new MyException("error");
     }
}

Upvotes: 0

Views: 1637

Answers (3)

Sazzadur Rahaman
Sazzadur Rahaman

Reputation: 7116

In your code resources are tried to be closed in several places, causes code duplication.

So you should use finally block to close resources like bellow:

 finally {
    if (pstm != null) {
        try {
           pstm.close();
        } catch (SQLException e) { /* ignored */}
    }

    if (conn != null) {
       try {
          conn.close();
       } catch (SQLException e) { /* ignored */}
    }
 }

Because what ever things happens, finally block will be executed before the return of the method call.

Upvotes: 2

Juned Ahsan
Juned Ahsan

Reputation: 68715

You can put your connection and statement close statements in finally block to be sure that those are closed no matter whether there is an exception or not. Finally is always exceuted when the try block exits. You can try something like this:

Connection conn = null;
PreparedStatement pstm = null;
try {
    conn = ConnectionManager.getConnection();
    pstm = conn.CreateStatement(statement);
    //set statement
    }catch (SqlException ex) {
        throw new MyException("error");
    }catch (ClassNotFoundException ex) {
   
        throw new MyException("error");
     }finally {
        if(conn != null) {
         try {
            pstm.close();
            conn.close();
         } catch (SQLException e) {  
           // throw or log the exception;
         }

        }
    }
}

Upvotes: 2

Masudul
Masudul

Reputation: 21961

in catch block should i close this two object or not?

No. Never close any object in catch block. To close any resource use finally{} block.

Upvotes: 4

Related Questions