break statement in finally clause java

Shwetanka picture Shwetanka · Jul 2, 2011 · Viewed 9.8k times · Source
  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

Answer

Stephen C picture Stephen C · Jul 2, 2011

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;
    }
}