S2095 FP in some cases

  • SonarQube 7.7
  • sonar-java 5.13.1

below case, always report “writer” not closed. try sonar-java 6.11, or newest SonarQube, no improve

case1:

public void updateIndexView() {
        log.info("start updating index.html");
        Map<String, String> params = new HashMap<>(1);
        params.put("ts", String.valueOf(System.currentTimeMillis()));
        BufferedWriter writer = null;
        try {
            String updatedHtmlString = HttpUtils.getAsString(staticFileLocation, params, null);
            log.info("get index.html finished, start writing local file.");
            Resource resource = new ClassPathResource("/static/index.html");
            File localHtmlFile = resource.getFile();
            writer = new BufferedWriter(new FileWriter(localHtmlFile));
            writer.write(updatedHtmlString);
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        } finally {
            log.info("updating index.html finished");
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

even case2:

public void updateIndexView() {
        log.info("start updating index.html");
        Map<String, String> params = new HashMap<>(1);
        params.put("ts", String.valueOf(System.currentTimeMillis()));
        BufferedWriter writer = null;
        FileWriter fw = null;
        try {
            String updatedHtmlString = HttpUtils.getAsString(staticFileLocation, params, null);
            log.info("get index.html finished, start writing local file.");
            Resource resource = new ClassPathResource("/static/index.html");
            File localHtmlFile = resource.getFile();
            fw = new FileWriter(localHtmlFile);
            writer = new BufferedWriter(fw);
            writer.write(updatedHtmlString);
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        } finally {
            log.info("updating index.html finished");
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {

                }
            }
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

Hello @neufeng ,

Could you please share what are the types (from which library you have them) used in your examples:

  • Resource
  • ClassPathResource
  • HttpUtils

It would allow us to validate your feedback on our side.

Thanks,
Michael

HttpUtils is a customized class,others as below
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

I found that when remove HttpUtils line or if (writer != null) line, no FP!!!