- 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.
- try-with-resources, can have catch and finally. They work as usual and no change in it.
- ARM returns the Suppressed Exception details thrown by close() statement without any add. coding
public class DirtyResource implements AutoCloseable
* Need to call this method if you want to access this resource
* @throws RuntimeException no matter how you call this method
public void accessResource()
throw new RuntimeException("I wanted to access this resource. Bad luck. Its dirty resource !!!");
* The overridden closure method from AutoCloseable interface
* @throws Exception which is thrown during closure of this dirty resource
public void close() throws Exception
throw new NullPointerException("Remember me. I am your worst nightmare !! I am Null pointer exception !!");
public class SuppressedExceptionDemoWithTryWithResource
* Demonstrating suppressed exceptions using try-with-resources
public static void main(String arguments) throws Exception
try (DirtyResource resource= new DirtyResource())
} catch ( Exception e1 )
[oracle@wls1 ARM]$ java SuppressedExceptionDemoWithTryWithResource
Exception in thread "main" java.lang.RuntimeException: I wanted to access this resource. Bad luck. Its dirty resource !!!
Suppressed: java.lang.NullPointerException: Remember me. I am your worst nightmare !! I am Null pointer exception !!
- Here we can easily indentify tha we are failing in ARM close() in DirtyResource.close