Java Programming Tutorials

Java programming tutorials with many code examples!

Java try with resources


Java 7 finally has shipped try with resources construct that simplifies very common use case when developer had to open some resource and then close in finally block after usage. try with resources makes it very simple. Learn how!


The following example shows the problem with the old, verbose approach and the new one, available since Java 7:


public class TryWithResources {

    static class CostlyResource implements AutoCloseable {

        public static CostlyResource open() {
            return new CostlyResource();

        public void close() {

    public static void main(String[] args) {

    private static void tryWithFinally() {
        CostlyResource resource = null;
        try {
            resource =;
            System.out.println("Old way: try with finally");
        } finally {
            // Have to check and call close() manually:
            if (resource != null) {

    private static void tryWithResources() {
        // CostlyResource.close() will be automatically called
        // at the and of the "try" block
        try (CostlyResource resource = {
            System.out.println("Java 7 way: Try with resources");

In the example I’ve created a sample resource – CostlyResource. It works the same as any other implementations of java.lang.AutoCloseable. As you can see the new version is much sorter and makes code more readable.

Running the code gives the following output:
Old way: try with finally
Java 7 way: Try with resources

Enjoy the new Java 7 feature! :-)

Was it helpful? Share!