Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break statement in finally clause java

  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

like image 704
Shwetanka Avatar asked Jul 02 '11 09:07

Shwetanka


2 Answers

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;
    }
}
like image 164
Stephen C Avatar answered Oct 24 '22 10:10

Stephen C


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.

like image 42
Saurabh Gokhale Avatar answered Oct 24 '22 10:10

Saurabh Gokhale