SonarQube A NullPointerException could be thrown; Conn is nullable here

359 views Asked by At

I have created the connection from HttpsURLConnection to set all the parameters to it. In the end finally block i am disconnecting it as showin below. But the SonarQube build is not passing. Showing as bug while disconnecting the connection.

Proxy proxy = new Proxy(Proxy.Type.HTTP, proxnet);    
HttpsURLConnection conn = (HttpsURLConnection)urlStr.openConnection(proxy);
con.set...();

finally{
   conn.disconnect();
}

SonarQube addressing the Bug inside finally block with NullPointerException.

keeping a NotNull check enough to the conn object? Or is anything to be done here apart from a not-null check? I am trying in different ways.

A "NullPointerException" could be thrown; "conn" is nullable here.

2

There are 2 answers

2
knittl On BEST ANSWER

Let me highlight the location of a possible exception:

Proxy proxy = new Proxy(Proxy.Type.HTTP, proxnet);    
HttpsURLConnection conn;
conn = (HttpsURLConnection)urlStr.openConnection(proxy) /* EXCEPTION! variable is not assigned */;
con.set...();

finally{
   conn.disconnect();
}

conn remains set to its initial value (null). The safe route is to add a null check in the finally block:

finally {
  if (conn != null) conn.disconnect();
}
0
MohammadMH On

when you put initiation on (HttpsURLConnection)urlStr.openConnection(proxy); it is possible to have an exception and don't initiate conn also finally will be run at any situation so sonar predicate a nullPointerException. maybe you need check conn != null before calling conn.disconnect(); in finally.