I have discovered possibility of having code "after return" using finally, here is some example:
int foo() {
BufferedReader br = ...;
try {
// cca 20 lines with 4 returns in different if-else clauses etc
//example:
if(something) {
return 0;
} else {
return 1;
}
} finally {
br.close();
}
}
As (in my opinion much more lazy) alternativity to:
int foo() {
BufferedReader br = ...;
int toReturn;
// cca 20 lines with 4 ASSIGMENTS in different if-else clauses etc
//example:
if(something) {
toReturn = 0;
} else {
toReturn = 1;
}
br.close();
return toReturn;
}
So, the question is, which is faster, more readable, and yes, in this case, i am really closing a BufferedReader, so is try-finnaly for this or am i using it wrong way?
Without using the
try/catch/finally
, if an exception is thrown, yourBufferedReader
won't be closed properly, causing a memory leak, potential unwanted file locking...Using
finally
, yourBufferedReader
will be closed, even if an exception is thrown while processing thetry
block.But as your
BufferedReader
instantiation can also throw an exception, you should include it in yourtry
block:If you're using Java 7 or newer, go with the elegant Try-with-resources, as stated by Arnaud.