Do you know Java: Use try-with-resource


Try-with-resource gives a safer way to handle exceptions and resources.

A quite big drawback of try-catch-finally that we have to close resource at the end, otherwise the resource remains locked - not always, but sometimes!

So either we try not to forget to close the resouce, and place finally at the end, or apply something that does this job instead of us.

Try-Catch-Finally

The hard part comes in finally, which encloses a try-catch, and null check is very easy to forget.

BufferedReader br = null; // has to be initialized
try {
    br = new BufferedReader(new CharArrayReader("apple".toCharArray()));
    // ...
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {  // try-catch
        if (br != null) { // null-check comes handy!
            br.close(); // to be handled or declared
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Try-With-Resource

By using try-with-resource, we can take off this burden off our shoulders. That is a much shorter and cleaner way to achieve the same without risking that we leave resources unclosed and no need to check nulls either.

try (BufferedReader br = new BufferedReader(new CharArrayReader("apple".toCharArray()))) {
    // ...
} catch (IOException e) {
    e.printStackTrace();
}
  1. No need to write finally
  2. Resource will be automatically closed (depends on the implementation)
  3. Resource has to implement AutoClosable interface

AutoClosable

What kinf of classes fit in the header of try-with-resource? Those, that implement AutoClosable.

public class ClosableResource implements AutoCloseable {
    @Override
    public void close() {
        System.out.println("closed!");
    }
}

close method is called automatically.

try (ClosableResource cr = new ClosableResource()) {
    // ...
} catch (...) {
    // ...
}

Closable vs AutoClosable

AutoClosable is the superinterface of Closable.

While Closable#close throws IOException, the AutoClosable#close throws exceptions derived from Exception.

Doc of AutoClosable
Doc of Closable
Further reading about try-with-resource

Code can be found: https://github.com/torokmark/do-you-know-java