java - how can suppressed exception in the 'try' block be retrieved? -


from java 7, can use 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() , br.close() both throw exceptions, readfirstlinefromfile throw exception try block (the exception of br.readline() ), , exception implicit block of try-with-resources statement (the exception of br.close() ) suppressed.

in case, can retrieve suppressed exceptions implicit block calling getsuppresed method from exception of try block this:

try {        readfirstlinefromfile("some path here..."); // method using try-with-resources statement }   catch (ioexception e) {     // exception try block       throwable[] suppressed = e.getsuppressed();     (throwable t : suppressed) {         // check t's type , decide on action taken     } } 

but suppose have work method written older version java 7, in block used:

static string readfirstlinefromfilewithfinallyblock(string path) throws ioexception {     bufferedreader br = new bufferedreader(new filereader(path));     try {         return br.readline();     } {         if (br != null) br.close();     } } 

then if br.readline() , br.close() once again both throw exceptions, situation reversed. method readfirstlinefromfilewithfinallyblock throw exception finally block (the exception of br.close() ), , exception try block (the exception of br.readline() ) suppressed.

so question here is: how can retrieve suppressed exceptions try block in second case?

source: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryresourceclose.html

you can't, basically. suppressed exception lost if br.close() throws.

the closest come have catch block assigns value locla variable:

static string readfirstlinefromfilewithfinallyblock(string path) throws ioexception {     ioexception exception = null;     bufferedreader br = new bufferedreader(new filereader(path));     try {       return br.readline();     } catch (ioexception e) {       exception = e;     } {       try {         if (br != null) br.close();       } catch (ioexception e) {         // both original call , close failed. eek!         // decide want here...       }       // close succeeded, had exception       if (exception != null) {         throw exception;       }     } } 

... only handles ioexception (rather unchecked exceptions) , horribly messy.


Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -