Sobes.tech
Middle

How does the try-with-resources operator work in Java?

sobes.tech AI

Answer from AI

The try-with-resources operator ensures automatic closing of resources that implement the java.lang.AutoCloseable interface.

Mechanism:

  1. In parentheses after the try keyword, one or more resources are declared and/or initialized, separated by semicolons.
  2. These resources must implement the AutoCloseable interface, which has a single method close():
    public interface AutoCloseable {
        void close() throws Exception;
    }
    
  3. After the try block completes (whether successfully or due to an exception), the Java machine automatically calls the close() method on each resource declared in parentheses, in the reverse order of their declaration.
  4. If exceptions are thrown in the try block or when closing resources:
    • If an exception is thrown both in the try block and when closing a resource, the exception from the try block is primary, and the exception during closing is suppressed and can be retrieved using the getSuppressed() method on the main exception.
    • If an exception is thrown only during resource closing, it propagates further.

Advantages:

  • Simplifies code and prevents resource leaks.
  • Eliminates the need for explicit close() calls in a finally block.
  • Properly handles cases where exceptions are thrown both in the main block and during resource closing.

Example:

Traditional approach with finally:

// Explicit resource closing in finally
BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("file.txt"));
    String line = reader.readLine();
    System.out.println(line);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using try-with-resources:

// Automatic resource closing
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
    String line = reader.readLine();
    System.out.println(line);
} catch (IOException e) {
    e.printStackTrace();
}

Multiple resources:

// Multiple resources, closed in reverse order of declaration
try (
    FileInputStream fis = new FileInputStream("in.txt");
    FileOutputStream fos = new FileOutputStream("out.txt")
) {
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = fis.read(buffer)) != -1) {
        fos.write(buffer, 0, bytesRead);
    }
} catch (IOException e) {
    e.printStackTrace();
}