Search code examples
javasonarqube

How to avoid sonar error "use try-with-resources or close this ... in a "finally" clause" if custom close method is used (java 6)?


Here's the code:

Connection connection = null;
    try {
        connection = createConnection();
        String sql = String.format(STRING_FOR_PROCEDURE, name);
        connection.createStatement().execute(sql);
        connection.commit();
    } catch (Exception e) {
        throw new DatabaseServiceException(e.getMessage(), e);
    } finally {
        closeConnection(connection);
    }

I suppose sonar wants me to close connection in block "finally" with something like this:

connection.close();

But I use custom method for this which is:

    protected void closeConnection(Connection connection) {
    try {
        if (connection != null) {
            connection.close();
        }
    } catch (SQLException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }
}

This method needs to be used in current class. But I receive sonar blocker "use try-with-resources or close this statement in a "finally" clause". Any ideas how to fix it?


Solution

  • Notice that your error is “use try-with-resources or close this statement in a "finally" clause.”

    The problem isn’t how you close your Connection. The problem is that you aren’t closing your Statement.

    Connection connection = null;
    Statement statement = null;
    try {
        connection = createConnection();
        String sql = String.format(STRING_FOR_PROCEDURE, name);
        statement = connection.createStatement();
        statement.execute(sql);
        connection.commit();
    } catch (Exception e) {
        throw new DatabaseServiceException(e.getMessage(), e);
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                Logger.log(Level.SEVERE, "Could not close Statement.", e);
            }
        }
        closeConnection(connection);
    }
    

    Remember that the statement needs to be closed before the Connection is closed.