After reading the byte code of the program, the code looks like this:
The statements of the finally block are queued before the return statement of the try block, so the return from the finally block is done first, and the original return statement never does.
For the program:
String test() { try { System.out.println("try"); return "1"; } finally { System.out.println("finally"); return "2"; } }
It is converted to:
String test() { System.out.println("try"); String s = "1"; //temporary variable System.out.println("finally"); return "2"; Exception exception; exception; System.out.println("finally"); return "2"; }
And For the program: with a catch block:
String test() { try { System.out.println("try"); return "1"; } catch (RuntimeException e) { System.out.println("catch"); return "2"; } finally { System.out.println("finally"); return "3"; } }
Converts to:
String test() { System.out.println("try"); String s = "1"; System.out.println("finally"); return "3"; RuntimeException e; e; System.out.println("catch"); String s1 = "2"; System.out.println("finally"); return "3"; Exception exception; exception; System.out.println("finally"); return "3"; }
Note. Done using JDK 1.7 and decompiled using Cavaj.
Rohit Totala Jul 28 '15 at 10:27 2015-07-28 10:27
source share