Skip to content

Try With Resources


There is a newer, and preferred form of the try/catch block. The new way is referred to as Try With Resources. Here's an example of the old way.

BufferedReader input = null;

try {
    input = new BufferedReader(new FileReader("sample.txt"));

    while (input.ready()) {
        System.out.println(input.readLine());
    }
} catch (FileNotFoundException fileNotFound) {
    System.out.println("There was a problem finding the file.");
    fileNotFound.printStackTrace();
} catch (IOException inputOutputException) {
    System.out.println("There was a problem reading the file.");
    inputOutputException.printStackTrace();
} catch (Exception exception) {
    System.out.println("There was a problem.");
    exception.printStackTrace();
} finally {

    try {
        if (input != null) {
            input.close();
        }
    } catch (Exception exception) {
        System.out.println("There was a problem closing the file.");
        exception.printStackTrace();
    }
}

And here is the code that uses the new form.

try (BufferedReader input = new BufferedReader(new FileReader("sample.txt"))) {

    while (input.ready()) {
        System.out.println(input.readLine());
    }
} catch (FileNotFoundException fileNotFound) {
    System.out.println("There was a problem finding the file.");
    fileNotFound.printStackTrace();
} catch (IOException inputOutputException) {
    System.out.println("There was a problem reading the file.");
    inputOutputException.printStackTrace();
} catch (Exception exception) {
    System.out.println("There was a problem.");
    exception.printStackTrace();
}

Syntax

The try statement has a set of parentheses.

  • try (...)

Anything opened inside the parentheses will be closed automatically.

  • try (BufferedReader input = new BufferedReader(new FileReader("sample.txt")))

Why This Matters: Resource Leaks

When your program opens a file, the operating system allocates a file handle — a limited system resource. If your program crashes, throws an exception, or simply forgets to call .close(), that file handle is never released. This is called a resource leak.

The finally block in the old pattern is supposed to guarantee cleanup, but it can be bypassed. The most common case: if a method has both a try block and a throws clause in its signature, a thrown exception can propagate before finally runs, leaving the file open.

Try-with-resources eliminates this problem. Any object declared in the try(...) parentheses is guaranteed to be closed when the block exits — whether it exits normally, via exception, or any other path. This works because Java calls .close() as part of the language specification, not as application logic.

The only requirement is that the object's class implements the AutoCloseable interface. BufferedReader, PrintWriter, FileReader, and all the stream classes used in this course implement it.

Use try-with-resources by default

In this course, and in professional Java code, try-with-resources is the expected pattern. The old finally-based form is shown first so you understand what the newer form replaced.


Multiple Resources

The resources statement can have multiple resources on multiple lines. There needs to be a semicolon at the end of all lines except the last one. Here's an example.

try (
    BufferedReader input = new BufferedReader(new FileReader("sample.txt"));
    PrintWriter output = new PrintWriter(new BufferedWriter(
            new FileWriter("foo.out")))
) {

    while (input.ready()) {
        output.println(input.readLine());
    }
} catch (FileNotFoundException fileNotFound) {
    System.out.println("There was a problem finding the file.");
    fileNotFound.printStackTrace();
} catch (IOException inputOutputException) {
    System.out.println("There was a problem reading the file.");
    inputOutputException.printStackTrace();
} catch (Exception exception) {
    System.out.println("There was a problem.");
    exception.printStackTrace();
}