3

Why does method return true if I change the value of r to false in finally?

boolean myMethod() {
    boolean r = true;
    try {
        throw new Exception("");
    } catch (Exception e) {
        return r;
    } finally {
        //System.out.println("executing finally");// will print if we uncomment this line
        r = false;
    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • Sorry guys, updated my question and code – Max Koretskyi May 15 '15 at 17:55
  • What compile time errors? I'm compiling it just fine in Java 7. – Makoto May 15 '15 at 17:57
  • 1
    @Makoto well, i guess it compiles now, after OP has updated his code. – QBrute May 15 '15 at 17:58
  • @Makoto Did you check this version https://stackoverflow.com/revisions/30265772/1? – Pshemo May 15 '15 at 17:58
  • 1
    Why would I check past revisions? Comments are temporal enough to exist at the moment that I read them. – Makoto May 15 '15 at 17:59
  • Why do you expect it to return false? – MadConan May 15 '15 at 18:00
  • I don't know who reopened this, but now that the code is fixed, that Q/A was the obvious duplicate. – Luiggi Mendoza May 15 '15 at 18:00
  • 3
    @LuiggiMendoza I reopened to change duplicate target. IMO new one is more precise. First duplicate looks like suggestion that `finally` block didn't execute, which was not true. – Pshemo May 15 '15 at 18:02
  • Already answered here: http://stackoverflow.com/questions/5708834/does-return-happen-after-finally – Guy Bouallet May 15 '15 at 18:04
  • 4
    @DrewKennedy You either misread answer in duplicate question, or you read old duplicate. `finally` will be executed, but changing value of `q` reference doesn't mean that it will also change value cached by `return` before it moved to `finally` block. To change such value we would need to add new `return` inside `finally` block like `finally { r = false; return r; }`. – Pshemo May 15 '15 at 18:09
  • @Pshemo Yeah I just tested it and, while knowing the finally block always executes, I actually thought it would be disregarded. I guess the finally block still executes as always, but the value change is disregarded. Kinda cool, actually. – Drew Kennedy May 15 '15 at 18:10
  • @DrewKennedy Yes that is one of many Java gotchas. – Pshemo May 15 '15 at 18:12

0 Answers0