public class FinallyTest {
static int i=0;
public static void main(String a[]){
while(true){
try{
i=i+1;
return;
}finally{
i=i+1;
break;
}
}
System.out.println(i);
}
}
In the above code output is '2'. What I was expecting was that nothing should be printed. What exactly does 'break' do here? Please explain. Thanks
The finally
clause changes the "completion reason" for the try clause. For a detailed explanation, refer to JLS 14.20.2 - Execution of try-catch-finally, with reference to JLS 14.1 Normal and Abrupt Completion of Statements.
This is one of those strange edge cases in the Java language. Best practice is not to deliberately change the control flow in a finally
clause because the behavior is difficult for the reader to understand.
Here's another pathological example:
// DON'T DO THIS AT HOME kids
public int tricky() {
try {
return 1;
} finally {
return 2;
}
}
Code in the finally clause is bound to execute.
Here's the flow :
So, after incrementing the value of i
to 1
in try block, it encounters the return statement. But, it has finally block too. So it executes finally block and their again, it increments the value of i
to 2
. Then the break in encountered and the loop is exited.
So, the value of i = 2
at the end. Hope the flow is clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With