Misreport on rule "Resources should be closed (java:S2095)"

the object stmtInstance got a issue “Use try-with-resources or close this “PreparedStatement” in a “finally” clause.”
why?

public void getData(String extractSql, Connection conn) {
		try {
			PreparedStatement stmtInstance = null;
			ResultSet resultSet = null;
			try {
				stmtInstance = conn.prepareStatement(extractSql); //got issue "Use try-with-resources or close this "PreparedStatement" in a "finally" clause."
				resultSet = stmtInstance.executeQuery();
			} catch (Exception e) {
				log.error("sql error:" + e.getMessage());
			} finally {
				try {
					if (stmtInstance != null) {
						stmtInstance.close();
					}
				} catch (Exception e) {
					log.error("ERROR:[{}]", e.getLocalizedMessage());
				}
				try {
					if (resultSet != null) {
						resultSet.close();
					}
				} catch (SQLException e) {
					log.error("ERROR:[{}]", e.getLocalizedMessage());
				}
			}

		} catch (Exception e) {
			log.error("ERROR:[{}]", e);
		}
	}

Hello @wangluo and welcome to the community!

According to the rule description objects, implementing Closable or AutoClosable should be closed after usage. And PreparedStatement does implement AutoClosable according to docs https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html

And if you look at documentation, you’ll find that in example PreparedStatement is created inside try-with-resources. So it will be closed after usage. According to docs, PreparedStatement should be closed automatically, once connection is closed, but it is recommended to close it explicitly to ensure proper cleanup.

Regards,
Margarita

Hi,
I’m facing the same false positive.
In the example of WANGLUO, the PreparedStatement is actually closed in the finally block.
So why is it still reported and how to fix it?