static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
if the methods readLine and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed. Why is the behaviour as such? Why is the exception from try block supressed?
Only exceptions within the
tryportion will be handled. Anything outside this (including thefinallysection isn’t covered by atryand as such, Exceptions aren’t handled.If you want to catch/suppress the exception inside the
finallyblock, you need to wrapif (br != null) br.close();with it’s own try/catch block, like this:Also, the exception from the
tryblock is suppressed because that’s the behavior of atryblock – to try something and give you a chance to recover. Since you don’t catch any exceptions after yourtryblock, no code is run in response to it.Then, whether or not any exception is thrown, the
finallyblock is executed. If it throws an exception, and because it’s not inside a try/catch block of its own, its Exception is propagated out the method, and to the calling method.To take the example from your comment below, as of Java 7, you’ll want to refer to the documentation outlined here, and focus on the second-to-last section entitled “Supressed Exceptions”, which basically says that multiple exceptions can be thrown out of a
tryblock, up to one exception per declared resource.As far as what happens if the resource declaration itself throws an exception, I don’t have JDK7 installed, so I’m not sure. Why not put the following code in a test project (exactly as it appears, with a bogus path), see what happens, and then tell us what the result it for everyone’s benefit: