org.sonar.l10n.java.rules.squid.S2093.html Maven / Gradle / Ivy
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.
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 (...) {}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy