versions used (SonarQube 9.1.0.47736 Community Edition, sonar-java-plugin-7.3.0.27589)
error observed: False positive scan as bug for submitted code Rule S2095 - Use try-with-resources or close this “PreparedStatement” in a “finally” clause. The bug is marked on the line where the PreparedStatement is returned from the Connection%prepareStatement call.
Scan the submitted code.
workaround? It seems to not show as a bug to change the order of the statements in the close.
The problem in this code is that rs.close() might throw an exception, which would prevent ps from being closed. I recommend using try-with-resources to avoid issues like this. Without try-with-resources closing multiple resources requires nested try-finally statements to prevent exceptions in one close methods from preventing the other close methods from executing.
PS: The issue goes away if you change the order because closing the prepared statement will automatically close the result set as well. So if you change the order, the call to rs.close() actually becomes redundant and SonarQube no longer cares whether it’s actually reached or not.