ARM - Automatic Resource Management(Introduced since Java 7)
Take a very simple example
static String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
Now if readLine()
function throws Exception and then even close()
function [in finally block] throws exception then the later is given more priority and is thrown back to the calling function. In this case the Exception thrown by the readLine() method is ignored/suppressed
. You can chain the causing exception in your exception and rethrow your exception from finally block.
Since java 7
functionality has been provided to retrieve suppressed Exceptions. You can call public final java.lang.Throwable[] getSuppressed()
function on the catched throwable object to view the suppressed Exceptions.
For Eg.
static String readFirstLineFromFileWithFinallyBlock(String path)
throws Exception {
try (BufferedReader br = new BufferedReader(new FileReader(path));) {
return br.readLine();
}
}
Now if br.readLine();
line throws Exception1
and then lets say Exception2
is thrown while closing the resource [Imagine this happening in an implicit finally block that try-with-resource statement creates] then Exception1 suppresses Exception2.
Few points to note here -
- If try-with-resource block throws exception i.e while resource instantiation then try block will not execute and the same exception will be thrown.
- If instantiation of resource is successful, try block throws an exception and exception is thrown while closing the resource then the exception thrown while closing resource is suppressed by the exception thrown from try block.
- If you provide explicit finally block and exception is thrown from that block it will suppress all other exception. (This explicit finally block executes after resources are closed)
I have compiled most of the possible scenarios with code snippets and output in following post.
Suppressed exceptions in java 7
Hope that helps.