Skip to lesson

Closing resources the old way

Before Java 7, the only safe way to close a resource was a finally block, because finally runs whether the code in try finishes or throws. The pattern works, but every detail of it is easy to get wrong.

try and finally with close

try-finally close means: open the resource, then put all the work in a try block and the close() call in its finally block. Java runs finally on every way out of the try: normal end, return, break or an exception.

Example 1 · close without finally, then with finally

FinallyCloseDemo.javaJava
import java.io.IOException;
class PretendFile {    private final String name;
    PretendFile(String name) throws IOException {        if (name.startsWith("missing")) {            throw new IOException("cannot open " + name);        }        this.name = name;        System.out.println("open " + name);    }
    String readLine() throws IOException {        if (name.startsWith("broken")) {            throw new IOException("read error in " + name);        }        return "data from " + name;    }
    void write(String text) {        System.out.println("write '" + text + "' to " + name);    }
    void close() throws IOException {        if (name.startsWith("usb")) {            throw new IOException("close failed: " + name + " was unplugged");        }        System.out.println("close " + name);    }}
public class FinallyCloseDemo {    static void withoutFinally(String name) throws IOException {        PretendFile f = new PretendFile(name);        System.out.println(f.readLine());        f.close();                       // skipped when readLine throws    }
    static void withFinally(String name) throws IOException {        PretendFile f = new PretendFile(name);        try {            System.out.println(f.readLine());        } finally {            f.close();                   // runs on every path        }    }
    public static void main(String[] args) {        System.out.println("Without finally:");        try {            withoutFinally("broken-marks.txt");        } catch (IOException e) {            System.out.println("Error: " + e.getMessage());        }
        System.out.println("With finally:");        try {            withFinally("broken-marks.txt");        } catch (IOException e) {            System.out.println("Error: " + e.getMessage());        }    }}
Output
Without finally:
open broken-marks.txt
Error: read error in broken-marks.txt
With finally:
open broken-marks.txt
close broken-marks.txt
Error: read error in broken-marks.txt

What this code does

  • In withoutFinally, readLine() throws, so control jumps straight out of the method and f.close() never runs. The file leaks.
  • In withFinally, the same exception happens, but finally runs first and prints close broken-marks.txt. Then the exception reaches main.

Open the resource before the try. If the open itself fails, there is nothing to close, and the finally never runs. Once the open succeeds, the finally guarantees the close.

The exception still travels to the caller after finally runs. finally closes; it does not catch.

The null check before close

Sometimes the open must sit inside the try, for example so that one catch handles both open and read errors. Then the variable is declared before the try and set to null, and the null check if (f != null) guards the close.

Example 2 · A failed open without and with the null check

NullCheckDemo.javaJava
import java.io.IOException;
class PretendFile {    private final String name;
    PretendFile(String name) throws IOException {        if (name.startsWith("missing")) {            throw new IOException("cannot open " + name);        }        this.name = name;        System.out.println("open " + name);    }
    String readLine() throws IOException {        if (name.startsWith("broken")) {            throw new IOException("read error in " + name);        }        return "data from " + name;    }
    void write(String text) {        System.out.println("write '" + text + "' to " + name);    }
    void close() throws IOException {        if (name.startsWith("usb")) {            throw new IOException("close failed: " + name + " was unplugged");        }        System.out.println("close " + name);    }}
public class NullCheckDemo {    static void bad(String name) throws IOException {        PretendFile f = null;        try {            f = new PretendFile(name);            System.out.println(f.readLine());        } finally {            f.close();                   // f is still null if the open failed        }    }
    static void good(String name) throws IOException {        PretendFile f = null;        try {            f = new PretendFile(name);            System.out.println(f.readLine());        } finally {            if (f != null) {                f.close();            }        }    }
    public static void main(String[] args) {        try {            bad("missing-fees.txt");        } catch (Exception e) {            System.out.println("bad:  caller sees " + e.getClass().getSimpleName());        }        try {            good("missing-fees.txt");        } catch (Exception e) {            System.out.println("good: caller sees " + e.getClass().getSimpleName()                    + " (" + e.getMessage() + ")");        }        try {            good("fees.txt");        } catch (Exception e) {            System.out.println("not printed");        }    }}
Output
bad:  caller sees NullPointerException
good: caller sees IOException (cannot open missing-fees.txt)
open fees.txt
data from fees.txt
close fees.txt

What this code does

  • In bad, the open throws, so f stays null and f.close() throws a NullPointerException. The caller sees that instead of the IOException.
  • In good, the check skips the close when nothing was opened, so the caller gets the real error. For an existing file it opens, reads and closes normally.

Without the check, a failed open leaves f as null, and f.close() in finally throws a NullPointerException. That new exception replaces the real one, so the caller sees a NullPointerException instead of "cannot open missing-fees.txt". The real error is lost.

Nested try blocks for two resources

Nested try-finally gives each resource its own try and finally. Open the first, start its try; inside it open the second and start a second try. The inner finally closes the second resource, the outer finally closes the first.

Example 3 · Two resources with nested try-finally

NestedCloseDemo.javaJava
import java.io.IOException;
class PretendFile {    private final String name;
    PretendFile(String name) throws IOException {        if (name.startsWith("missing")) {            throw new IOException("cannot open " + name);        }        this.name = name;        System.out.println("open " + name);    }
    String readLine() throws IOException {        if (name.startsWith("broken")) {            throw new IOException("read error in " + name);        }        return "data from " + name;    }
    void write(String text) {        System.out.println("write '" + text + "' to " + name);    }
    void close() throws IOException {        if (name.startsWith("usb")) {            throw new IOException("close failed: " + name + " was unplugged");        }        System.out.println("close " + name);    }}
public class NestedCloseDemo {    static void copy(String from, String to) throws IOException {        PretendFile in = new PretendFile(from);        try {            PretendFile out = new PretendFile(to);            try {                out.write(in.readLine());            } finally {                out.close();             // inner finally: the second resource            }        } finally {            in.close();                  // outer finally: the first resource        }    }
    public static void main(String[] args) {        System.out.println("Copy 1:");        try {            copy("marks.txt", "report.txt");        } catch (IOException e) {            System.out.println("Error: " + e.getMessage());        }
        System.out.println("Copy 2:");        try {            copy("marks.txt", "missing-folder/report.txt");        } catch (IOException e) {            System.out.println("Error: " + e.getMessage());        }    }}
Output
Copy 1:
open marks.txt
open report.txt
write 'data from marks.txt' to report.txt
close report.txt
close marks.txt
Copy 2:
open marks.txt
close marks.txt
Error: cannot open missing-folder/report.txt

What this code does

  • Copy 1 closes report.txt (inner finally) before marks.txt (outer finally): reverse order of opening.
  • In copy 2 the second open fails. The inner try is never reached, but the outer finally still closes marks.txt.

Example 4 · The same pattern with real files

OldStyleCopyDemo.javaJava
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class OldStyleCopyDemo {    static void copyTopper(Path from, Path to) throws IOException {        BufferedReader in = Files.newBufferedReader(from);        try {            BufferedWriter out = Files.newBufferedWriter(to);            try {                out.write("Topper: " + in.readLine());                out.newLine();            } finally {                out.close();            }        } finally {            in.close();        }    }
    public static void main(String[] args) throws IOException {        Path folder = Files.createTempDirectory("results");        Path marks = folder.resolve("marks.txt");        Path report = folder.resolve("report.txt");        Files.writeString(marks, "Meera,96\nKabir,88\n");
        copyTopper(marks, report);        System.out.println(report.getFileName() + ": " + Files.readString(report).trim());
        Files.delete(marks);        Files.delete(report);        Files.delete(folder);    }}
Output
report.txt: Topper: Meera,96

What this code does

  • Files.newBufferedWriter(to) opens a file for writing; write and newLine put text in it. The Reading and Writing Text Files module covers them.
  • About a dozen lines of nesting just to copy one line safely. Every new resource adds another try and finally, which is why Java 7 added a shorter form.
  • Open A, then try {
  • Open B, then try { ... work ... } finally { B.close(); }
  • } finally { A.close(); }

This closes the resources in reverse order of opening, and it closes the first one even when the second fails to open. Each extra resource adds another level of nesting.

Why this code is easy to get wrong

The pattern is long, so people shorten it. The most common shortcut puts both closes in one finally. If the first close() throws, the second line never runs and the second resource leaks.

Example 5 · Bug: two closes in one finally

OneFinallyBugDemo.javaJava
import java.io.IOException;
class PretendFile {    private final String name;
    PretendFile(String name) throws IOException {        if (name.startsWith("missing")) {            throw new IOException("cannot open " + name);        }        this.name = name;        System.out.println("open " + name);    }
    String readLine() throws IOException {        if (name.startsWith("broken")) {            throw new IOException("read error in " + name);        }        return "data from " + name;    }
    void write(String text) {        System.out.println("write '" + text + "' to " + name);    }
    void close() throws IOException {        if (name.startsWith("usb")) {            throw new IOException("close failed: " + name + " was unplugged");        }        System.out.println("close " + name);    }}
public class OneFinallyBugDemo {    static void copy(String from, String to) throws IOException {        PretendFile in = null;        PretendFile out = null;        try {            in = new PretendFile(from);            out = new PretendFile(to);            out.write(in.readLine());        } finally {            if (in != null) {                in.close();              // throws for the unplugged USB file            }            if (out != null) {                out.close();             // never reached            }        }    }
    public static void main(String[] args) {        try {            copy("usb-marks.txt", "report.txt");        } catch (IOException e) {            System.out.println("Error: " + e.getMessage());        }    }}
Output
open usb-marks.txt
open report.txt
write 'data from usb-marks.txt' to report.txt
Error: close failed: usb-marks.txt was unplugged

What this code does

  • in.close() throws because the USB drive was unplugged, so the next line out.close() never runs. There is no close report.txt line: the report file leaks.
  • The fix in old code is a separate try-finally per resource (Example 3), or a try/catch around each close(). Both make the code even longer.
  • close() outside finally: skipped by any exception.
  • No null check: NullPointerException hides the real error.
  • Two closes in one finally: the second is skipped if the first throws.
  • An exception from close() replaces the body's exception.

There is a second, quieter problem. If the work in try throws and then close() in finally also throws, the exception from close() replaces the first one. The caller sees "close failed" and never learns what really went wrong. The Suppressed exceptions lesson shows how try-with-resources solves this.

Find the bug

Find the close mistake

Select the line that is wrong.

Both files must always be closed, even when copy() throws.

Round 1 of 3

Next step

Check your understanding

12 quick questions