Break at the end of a java sentence

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, the output is "2". I expected that nothing should be printed. What exactly does the β€œbreak” take here? Please explain. Thanks

+8
java try-catch-finally break
source share
4 answers

The finally clause modifies the termination argument for the try clause. For a detailed explanation, see JLS 14.20.2 - Executing try-catch-finally with reference to JLS 14.1 Normal and abrupt completion of statements .

This is one of those weird Java cases. Best practice is to not intentionally change the flow of control in a finally clause because reader behavior is hard to understand.

Here is another pathological example:

 // DON'T DO THIS AT HOME kids public int tricky() { try { return 1; } finally { return 2; } } 
+10
source share

It interrupts the cycle and "redefines" the return.

  • finally locks always execute
  • what happens in finally can override what happened before - throws exceptions, returns instructions.
+4
source share

The code in the finally clause must execute.

Here's the thread:

So, after increasing the value of i to 1 in the try block, it encounters a return statement. But finally, it is also blocked. Thus, it executes the final block and them again, it increases the value of i to 2 . Then the gap opens and the cycle ends.

So, the value i = 2 at the end. Hope the stream is transparent.

+4
source share
 public static void main(String a[]) { while(true) <<< #1 { try { i=i+1; <<< #2 return; } finally { i=i+1; <<< #3 break; <<< #4 } } System.out.println(i); <<< #5 } 

This shows BlueJ Tracing.

0
source share

All Articles