The main objective of try-with-resources in Java is the automatic and correct release of resources. Before the introduction of this construct in Java 7, developers had to manually close resources in the finally block. This led to code duplication and frequent errors.
In Java 6 and earlier, resources (open files, streams, connections) had to be managed manually through finally, which often led to leaks.
Manually written resource closing code is a source of bugs, especially when dealing with multiple exceptions and complex catch block hierarchies. There is no guarantee that close() will be called in case of errors.
With Java 7, the try-with-resources syntax was introduced, which ensures that the close() method is automatically called for each resource that implements the AutoCloseable interface.
Example code:
try (BufferedReader reader = new BufferedReader(new FileReader("test.txt"))) { String line = reader.readLine(); System.out.println(line); } catch (IOException e) { e.printStackTrace(); } // reader is automatically closed
Key features:
AutoCloseable interface can be used in try-with-resources.Question 1: Which interface must a resource implement for try-with-resources?
AutoCloseable. Any object implementing this interface (or Closeable) can be used in this construct.
Question 2: In what order are resources closed if there are multiple in try-with-resources?
Resources are closed in the reverse order of their declaration (LIFO stack):
try (A a = new A(); B b = new B()) { ... } // b.close() will be called first, then a.close()
Question 3: Can you use try-with-resources for non-standard objects, such as a network connection that does not implement AutoCloseable?
No, but you can implement AutoCloseable manually in your class. After that, the object will become compatible with try-with-resources.
Developers manually closed JDBC Connection and Statement via finally. When a second exception occurred, the Statement was not closed, the connection "hung" and hid the error.
Pros:
Cons:
After implementing try-with-resources in the file loading module, all streams are closed automatically, the code became much shorter, and file descriptor leak bugs disappeared.
Pros:
Cons: