Description
Java 1.7 introduced the try-with-resource block which is more succinct than the usual try-finally-block. It should be used whenever possible.
Type
Code Smell
Snippet
public class ResourceNotManagedWithTryWithResource {
public static class Auto implements AutoCloseable {
@Override
public void close() {
// close resources...
}
}
public static void main(String[] args) {
Auto auto = new Auto(); // Noncompliant
try {
// do something with auto...
} finally {
auto.close();
}
try(Auto betterAuto = new Auto()) { // Compliant
// do something with betterAuto...
}
}
}
Hi,
There is a rule called Try-with-resources should be used (SQUID:2093). This rule adds an issue when an object is created inside try block and next closed in finally block. Lets see how it works:
if object is created in try and next closed in finally, SonarJava creates an issue:
Thanks for pointing that out. Yes, then it should be bug-report instead of a new rule suggestion. Sometimes, one claims the resource from outside the try-block in order to avoid uninitialized or null variables.