通过 finally 块中的方法关闭其他 class 中的连接对象

Closing connection's object in other class through a method in finally block

我正在使用 Sonar 工具分析现有应用程序中的编码标准,我遇到了 Sonar 规则:"Close the resources" 其中 Connection 的对象 conn 是罪魁祸首。

正如我们所知,我们应该使用 conn.close(); 关闭 Connection 对象,但是在 Application 中调用了释放连接的方法。

下面是一段代码,其中 Connection 对象通过 finally 块中名为 releaseConnection() 的方法关闭。

finally {
    try {
        OtherClass.releaseConnection(conn); // Line: 50 Here is the call to close the conn
    } 
    catch (SomeException se) {
        LOGGER.error(" Exception while releaseConnection in add() method : ",se);
    }
}

关闭方法:

 public static void releaseConnection(Connection conn) throws DBException {
    if (conn!=null) {
        try {
            if (!conn.isReadOnly()){
                conn.commit();
            }
        } catch (SQLException e) {
            LOGGER.error("Error while commiting the connection. " + e);
            rollback(conn);
            throw new SomeException(e,SOMETHING);
        } finally {
            try {conn.close();} catch (SQLException se){
                LOGGER.error("releaseConnection() Error  " + se);
            } 
        }
    }
} 

这是我关注的问题列表:

  1. 因为这个现有的实现正在做正确的事情(如果我错了请纠正我)是否真的需要根据 Sonar 建议更改代码。

  2. 如果我真的需要遵循 Sonar 的建议,最好的方法应该是什么。

更新:

我怎样才能 ignore/bypass 一些特定的代码或规则并应用到我上面的代码中。 假设我想忽略第 50 行,我该怎么做?

我不想弄乱上面的代码,但我真的想忽略它并减少我的问题。提前致谢。

您实际上遇到了符号执行引擎的限制(此规则在后台使用):https://jira.sonarsource.com/browse/SONARJAVA-1591

这里发生的事情是,我们通过跳过整个 try 块的执行路径(以简化流程的处理)来近似 try/catch/finally 中的执行流程,这会导致误报提到是因为我们没有看到对您的方法的调用可以防止问题被引发。

没错! Sonar 不会检查是否从 finally 块调用任何方法来关闭资源。它只是检查资源的关闭。