CodeBlanks Logo Icon CodeBlanks

try-with-resources

Learn automatic close with try-with-resources.

try-with-resources

Introduced in Java 7, try-with-resources automatically closes resources like files. The resource is declared at the start of the try block; when the block ends, Java calls close() automatically. The BufferedReader r = new BufferedReader(...) resource goes inside the try parentheses.

This structure removes the risk of forgetting close(). The resource must implement AutoCloseable; most Java I/O classes do. Multiple resources are separated by semicolons.

The AutoCloseable interface

For a class to be used in try-with-resources, it must implement AutoCloseable. This interface has one method: void close() throws Exception. When you write your own resource classes, you implement this interface and override close.

If the try block throws and close also throws, the close exception is added as suppressed to the main exception; it is not lost. Access it with Throwable.getSuppressed().

Practice Read a file with try-with-resources

Import java.io.BufferedReader, java.io.FileReader, java.io.FileWriter and java.io.IOException. Add throws IOException to main. First write a file: FileWriter fw = new FileWriter("k.txt"); fw.write("Line"); fw.close();. The main task: in a try (BufferedReader r = new BufferedReader(new FileReader("k.txt"))) block, print System.out.println(r.readLine());. Do not call close; try-with-resources handles it.

Starter code

Main.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        // First write one line to a file with FileWriter

        // Open BufferedReader with try-with-resources and print readLine

    }
}

Sample solution

Main.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        FileWriter fw = new FileWriter("k.txt");
        fw.write("Line");
        fw.close();
        try (BufferedReader r = new BufferedReader(new FileReader("k.txt"))) {
            System.out.println(r.readLine());
        }
    }
}

Expected output

Line

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the try-with-resources header

Question
try (BufferedReader r = new BufferedReader(new FileReader("a.txt"____)) {
    System.out.println(r.readLine());
}
Answer
try (BufferedReader r = new BufferedReader(new FileReader("a.txt"))) {
    System.out.println(r.readLine());
}

Explanation: Two closing parens close FileReader and BufferedReader.

2 What does try-with-resources guarantee?

  • The resource is never opened
  • Exceptions are never thrown
  • The file is deleted automatically
  • The resource is closed automatically Correct answer

Explanation: try-with-resources calls close automatically at the end of the block.

3 Match the try-with-resources concepts

Term Meaning
AutoCloseable Interface required for resources
close() Method called automatically
suppressed Exception from close, attached
try (...) Resource declaration

All lessons in Intermediate