Monday 27 June 2011

try-with-resources statement


This is simply beautiful and incredibly reassuring for the simple reason that resource closing is not only automatic and requires a lot less code but if in the examples below multiples exceptions are thrown (i.e. one in the closing of the resource and one in the use of the resource) then not only does the latter not get swallowed (unlike pre-java-7) but finally you can access all suppressed exceptions (i.e. the former) via the new API.


public class TryWithResources {

static class MyResource1 implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("MyResource1 was closed!");
}
}

static class MyResource2 implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("MyResource2 was closed!");
}
}

public static void main(String[] args) throws Exception {
/*
         * close() methods called in opposite order of creation
         */
try (MyResource1 myResource1 = new MyResource1();
MyResource2 myResource2 = new MyResource2()) {}
}

}


NOTE: In the above example the resources are closed in an order opposite to their order of creation.

No comments:

Post a Comment