SonarQube shows error even when implemented the suggestions

768 views Asked by At

On doing a code analysis of the below code in SonarQube, I found that i suggests to close the HttpClient.

import org.apache.http.impl.client.CloseableHttpClient;

public void request() {
    CloseableHttpClient httpclient = null;

    try {
        httpclient = HttpClients.createDefault();

        /**
         * Rest of the code
         */
    } catch(IOException e) {
        LOGGER.error("Error in processing : {}", e.getMessage(), e);
    } finally {
        try {
            if(httpclient != null) {
                httpclient.close();
            }
        } catch(IOException e) {
            LOGGER.error("Error in closing client : {}", e.getMessage(), e);
        }
    }
}

SonarQube still complains that httpclient should be closed, even though I am closing it in the finally block.

The error given by SonarQube:

Close this "CloseableHttpClient".

Java - 1.8 SonarQube - 5.6

Any ideas what I might be doing wrong. Thanks

1

There are 1 answers

0
AlkaRocks On

Use a try with resources

public void request() {
   try (CloseableHttpClient httpclient = HttpClients.createDefault()){
    /**
     * Rest of the code
     */
   } catch(IOException e) {
       LOGGER.error("Error in processing : {}", e.getMessage(), e);
   } 
}