From Java 7, we can use the try-with-resources statement:
static String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } }
if br.readLine() and br.close() both throw an exception , readFirstLineFromFile will throw an exception from the try block (an exception from br.readLine() ), and an exception will be thrown from the implicit finally block of the try-with-resources statement ( br.close() exception br.close() ) will be suppressed.
In this case, we can get suppressed exceptions from the implicit finally block by calling the getSuppresed method from the exception, try the block as follows:
try { readFirstLineFromFile("Some path here..."); // this is the method using try-with-resources statement } catch (IOException e) { // this is the exception from the try block Throwable[] suppressed = e.getSuppressed(); for (Throwable t : suppressed) { // Check t type and decide on action to be taken } }
But suppose we need to work with a method written in an older version than Java 7, which uses the finally block:
static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException { BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readLine(); } finally { if (br != null) br.close(); } }
then if br.readLine() and br.close() again both throw an exception , the situation will be canceled. The readFirstLineFromFileWithFinallyBlock method will throw an exception from the finally block ( br.close() exception), and an exception from the try block ( br.readLine() exception) will be suppressed.
So my question is: how can we extract the excluded exceptions from the try block in the second case?
Source: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
source share