typestar

try-with-resources in Java

Deterministic cleanup: whatever the try opened, it closes.

import java.io.BufferedReader;
import java.io.StringReader;
import java.io.StringWriter;

// try-with-resources closes whatever it opened, success or failure
try (var reader = new BufferedReader(new StringReader("one\ntwo"))) {
    System.out.println(reader.readLine());
    System.out.println(reader.readLine());
}

// several resources close in reverse order of opening
try (var a = new StringWriter(); var b = new StringWriter()) {
    a.write("closed in");
    b.write("reverse order");
    System.out.println(a + " " + b);
}

How it works

  1. Resources declared in the parentheses close at the brace.
  2. Success or exception, the close still happens.
  3. Several resources close in reverse order of opening.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
509
Tokens
110
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 73 seconds.

Type this snippet

Step 3 of 3 in Errors & files, step 27 of 29 in Language basics.

← Previous Next →