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.
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){...}
}
}
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 (...) {}