Java 7 introduced the try-with-resources statement, which guarantees that the resource in question will be closed. Since the new syntax is closer to bullet-proof, it should be preferred over the older ``++try++``/``++catch++``/``++finally++`` version.


This rule checks that ``++close++``-able resources are opened in a try-with-resources statement.


*Note* that this rule is automatically disabled when the project's ``++sonar.java.source++`` is lower than ``++7++``.


== Noncompliant Code Example

----
FileReader fr = null;
BufferedReader br = null;
try {
  fr = new FileReader(fileName);
  br = new BufferedReader(fr);
  return br.readLine();
} catch (...) {
} finally {
  if (br != null) {
    try {
      br.close();
    } catch(IOException e){...}
  }
  if (fr != null ) {
    try {
      br.close();
    } catch(IOException e){...}
  }
}
----


== Compliant Solution

----
try (
    FileReader fr = new FileReader(fileName);
    BufferedReader br = new BufferedReader(fr)
  ) {
  return br.readLine();
}
catch (...) {}
----
or

----
try (BufferedReader br = 
        new BufferedReader(new FileReader(fileName))) { // no need to name intermediate resources if you don't want to
  return br.readLine();
}
catch (...) {}
----


== See

* https://wiki.sei.cmu.edu/confluence/x/6DZGBQ[CERT, ERR54-J.] - Use a try-with-resources statement to safely handle closeable resources


ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]
