abhinaw
abhinaw

Reputation: 1

SonarQube issue: Method may fail to clean up stream or resource on checked exception

The following statement in my code is being red-marked by SonarQube as a critical issue. stmt=conn.createStatement();

The exact issue is, "method may fail to clean up java.sql.Statement on checked exception".

Code snippet below:

.
.
.
try{
    .
    .
    .

    **stmt=conn.createStatement();**

    .
    .
    .
} catch (SQLException e) {
    ...exception logged... 
} catch (NullPointerException e) {
    ...exception logged...
}finally{

    try {
            if(rs !=  null)
            {
                    rs.close();
            }
        } catch (SQLException e) {
        ...exception logged...
    }

    if(stmt !=  null)
    {
        try {
            stmt.close();
        } catch (SQLException e) {

            ...exception logged...
        }catch (NullPointerException e) {
            ...exception logged...
        }
    }

    if(conn !=  null)
    {
        try {
            conn.close();
        } catch (SQLException e) {
            ...exception logged...              }
    }

}
.
.
.

The rule shown by SonarQube is as below:

Method may fail to clean up stream or resource on checked exception This method may fail to clean up (close, dispose of) a stream, database object, or other resource requiring an explicit cleanup operation. In general, if a method opens a stream or other resource, the method should use a try/finally block to ensure that the stream or resource is cleaned up before the method returns. This bug pattern is essentially the same as the OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE bug patterns, but is based on a different (and hopefully better) static analysis technique. See Weimer and Necula, Finding and Preventing Run-Time Error Handling Mistakes, for a description of the analysis technique. . findbugs:OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE Sep12 Reliability > Exception handling

I have closed all the connections, statements and resultsets. What might be the issue here?

Upvotes: 0

Views: 1432

Answers (1)

Vinod Jayachandran
Vinod Jayachandran

Reputation: 3898

From this message method may fail to clean up java.sql.Statement on checked exception, my suspect is you are specific exception like NPE or SqlException. Try to catch Exception as a whole and try if it works . Reference as below.

try {
        if(rs !=  null)
        {
                rs.close();
        }
    } catch (Exception e) {
    ...exception logged...
}

if(stmt !=  null)
{
    try {
        stmt.close();
    } catch (Exception e) {

        ...exception logged...
    }
}

if(conn !=  null)
{
    try {
        conn.close();
    } catch (Exception e) {
        ...exception logged...              }
}

Upvotes: 0

Related Questions