New/strange Java "try()" syntax?

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


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.


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.