简体   繁体   中英

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");
     }
}

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.

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;
         }

        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM