0

Possible Duplicate:
Java try-finally return design question

Consider the following method:

public boolean test() {
   try {
      return false;
   } finally {
      return true;
   }
}

Why does it return true? I know that the finally part is executed always, but should it first execute the try part and the return true and exit the method? Can someone explain me in simple words why Java exactly acts like this? I think it is very counter-intuitive.

Community
  • 1
  • 1
  • 1
    Why *shouldn't* `finally` run on method exit? The only part that I'd consider counter-intuitive is that `return` is allowed in `finally` at all. –  Nov 22 '11 at 18:38
  • `finally` simply means "do this last, every time" (even if an exception is thrown). It doesn't quite make sense in this case and I've never seen code like this, but it's typically used for closing streams or files, or any cleanup that needs to be done before leaving a method, regardless of how that method executed. – Nate W. Nov 22 '11 at 18:39
  • Wow, java actually *will* allow you to shoot yourself in the foot! – Kevin Nov 22 '11 at 18:43
  • @esaj it's not really a duplicate. he returns true in the try block. –  Nov 22 '11 at 18:44
  • 3
    @Roflcoptr: Oh, in that case... ;) No, it's still a duplicate =P – esaj Nov 22 '11 at 18:46
  • 1
    It returns true because the code of a finally block is always executed last. If it makes you feel better, the return in the try block is actually executed - the finally just overrides the returned data. Think back to your C days and it will make complete sense. – Perception Nov 22 '11 at 18:49
  • @Roflcoptr: I could've sworn having the same method name and signature would be enough... ;) – BoltClock Nov 22 '11 at 18:49

2 Answers2

2

Essentially, the contract of a finally block is that it is always executed no matter what happens in the try block. This is why true is returned.

Further reading: http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
2

As "finally" always executes, it is executed before relinquishing the control flow outside the method i.e returning.

But if the JVM halts in the try block, finally will not be executed.

Mechkov
  • 4,294
  • 1
  • 17
  • 25