64

While messing around with the custom formatting options in Eclipse, in one of the sample pieces of code, I saw code as follows:

/**
 * 'try-with-resources'
 */
class Example {
    void foo() {
        try (FileReader reader1 = new FileReader("file1"); FileReader reader2 = new FileReader("file2")) {

        }
    }
}

I've never seen try used like this and I've been coding in Java for 9 years! Does any one know why you would do this? What is a possible use-case / benefit of doing this?

An other pieces of code I saw, I thought was a very useful shorthand so I'm sharing it here as well, it's pretty obvious what it does:

/**
 * 'multi-catch'
 */
class Example {
    void foo() {
        try {
        } catch (IllegalArgumentException | NullPointerException | ClassCastException e) {
            e.printStackTrace();
        }
    }
}
5
  • 4
  • 6
    The use case benefit is that the resources you open in the try parens are closed for you automatically without needing another try catch in your finally block. Also the catch block allows multiple exceptions so you avoid duplicate code. Commented Apr 11, 2012 at 23:16
  • 9
    It is very similar to the C# using statement, if you are familiar with C#: msdn.microsoft.com/en-us/library/yh598w02.aspx Commented Apr 11, 2012 at 23:17
  • 2
    See Java 7 SE new features.
    – Eng.Fouad
    Commented Apr 11, 2012 at 23:20
  • 1
    @HunterMcMillen Thanks Hunter, that's a pretty clear and concise explanation. I did try to google it but I wasn't quite sure what to google for, I didn't realize that it may have been added in Java 7 I just assumed it had been there all along and I just didn't know about it.
    – Ali
    Commented Apr 11, 2012 at 23:49

8 Answers 8

71

It was added in Java 7. It's called the try-with-resources statement.

/edit

Might as well throw this in here too. You can use the try-with-resources statement to manage Locks if you use a wrapper class like this:

public class CloseableLock implements Closeable {
    private final Lock lock;

    private CloseableLock(Lock l) {
        lock = l;
    }

    public void close() {
        lock.unlock();
    }

    public static CloseableLock lock(Lock l) {
        l.lock();
        return new CloseableLock(l);
    }
}

try(CloseableLock l = CloseableLock.lock(lock)) { // acquire the lock
    // do something
} // release the lock

However, since you have to declare a variable for every resource, the advantage of this is debatable.

1
  • 2
    "Might as well throw this in here" - What is meant by that?
    – sofs1
    Commented Feb 22, 2017 at 12:05
10

This is Java 7's new try-with-resources statement: http://download.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html

6

Those are changes introduced in JDK7.

First statement is a try-with-resources. I don't know exactly why they exist but exceptions are often caused by inputstreams etc, I guess it just improves readability. Edit: thanks to the other answerers, I read the javadoc and I now know that it will close all i/o streams that implement AutoCloseable, omitting the need for a finally block in a lot of situations

Second is a multi-catch, which is really handy when you have different exceptions that you handle in exactly the same way.

1
  • 2
    Just use them: then the purpose of their existence will become clear.
    – user166390
    Commented Apr 11, 2012 at 23:24
3

Same usage as using(Resource) in C Sharp,which means this resource will be automatic recycled when your program has leaven out of this code block.(Just my opinion)

The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource

The try-with-resources Statement

2
  • By the way ,this usage was added in Java7 .
    – Chopping
    Commented Jun 13, 2018 at 12:03
  • So the resources are automatically disposed/closed?
    – Flimtix
    Commented Apr 22, 2022 at 7:48
2

It's called try-with-resource. It's a way so as to not have to clean after yourself as the language will do it for you.

1

it was added in java 7. It is called try with resources. Try with resources statement feature was introduced in java 7 version. Try with resource statement is a try statement that declares one or more statements. A resource is an object that must be closed after the program is finished with it.

Before java 7 we use finally block to close the resources that we have used in our program. In finally block we have to close all the resources manually that we have used in our program. For more information you can visit try with resources

0

That is called with a try with resources. in a try with resources, any kind of closable stream declared in the resources section will be closed after the try statement is done. So it pretty much is a

try{
InputStream is;
//Stuff
}finally{
is.close()
}
1
  • It's actually quite a bit more than that, it also handles exceptions in the close() call in a defined way. If it were only this, then there would hardly be a reason to introduce it. Commented Apr 12, 2012 at 7:58
0

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Not the answer you're looking for? Browse other questions tagged or ask your own question.