← Java from Scratch Lesson 54 of 88 · 10 XP

try-with-resources

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Files, network connections and databases have to be closed, even if an error happened along the way. The old way is finally { r.close(); }. Since Java 7 there's try-with-resources:

try (BufferedReader r = new BufferedReader(new FileReader("data.txt"))) {
    System.out.println(r.readLine());
}   // r.close() is called by itself — both on success and on an exception

A resource is any object that implements AutoCloseable (it has one method, close()). There can be several resources, separated by ; — they're closed in reverse order: the last one opened is closed first.

Task. Finish class Resource implements AutoCloseable: in the constructor it prints open <name>, in close() — close <name>, in use() — use <name>, and if the name is bad, it throws IllegalStateException("broken"). In main, for each line with a pair of names, open both resources in one try-with-resources, call use() on both, and print an error as error: broken.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.