ProgrammingBackend Developer

What is try-with-resources in Java, how does it differ from the classic try-catch-finally block, and when should it be used?

Pass interviews with Hintsage AI assistant

Answer.

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.

Background

In Java 6 and earlier, resources (open files, streams, connections) had to be managed manually through finally, which often led to leaks.

Problem

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.

Solution

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:

  • All resources are guaranteed to be closed even in case of exceptions.
  • Only objects that implement the AutoCloseable interface can be used in try-with-resources.
  • The boilerplate code is simplified and reduced, decreasing the likelihood of leaks.

Trick questions.

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.

Common mistakes and anti-patterns

  • Forgetting to handle exceptions thrown in close()
  • Using try-with-resources with classes that do not implement AutoCloseable
  • Unclosed resources in legacy code that uses outdated finally

Real-life example

Negative case

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:

  • Control over the order of closing.
  • Explicit resource management.

Cons:

  • Risk of forgetting to close the resource.
  • Connection leaks.

Positive case

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:

  • Reliability.
  • Conciseness of code.
  • Convenient testing.

Cons:

  • Requirement to implement AutoCloseable.
  • Not immediately available in older versions of Java.