[Java] S2093: False-Negatives: Resource not managed with try-with-resource

java

(Werner Thumann) #1

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...
		}
	}
	
}

Note
Also covered by Eclipse JDT.


(Adam Gabryƛ) #2

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:

  • if you use try-with-resources then everything is okay:
    okay

  • if object is created before try and next closed in finally, no issues are reported. I think it is a wrong behavior and you hit a false negative:
    false-negative

Environment:

  • SonarQube 7.3
  • SonarJava 5.8
  • SonarScanner for Maven 3.5.0.1254

Project:

Cheers


(Werner Thumann) #3

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.


(Alexandre Gigleux) #4

Hello Werner, Adam,

Ticket created: https://jira.sonarsource.com/browse/SONARJAVA-2939

Thanks