1

If I run the following code:

try{
   return false;
} catch(Exception e){
       e.printStackTrace();
}
finally{
   return true;
}

why does it return true?

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225
Radu
  • 83
  • 2
  • 9
  • 3
    possible duplicate of [Does finally always execute in Java?](http://stackoverflow.com/questions/65035/does-finally-always-execute-in-java) – Daniel Jun 26 '13 at 14:59
  • This is *bad*. Never, never, exit a finally block with return/throw/break/continue. Never let an exception propagate out of the `finally` block. – devnull Jun 26 '13 at 15:24

5 Answers5

4

From the Java Language Specification section 14.20.2

  • If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and then there is a choice:
    • If the finally block completes normally, then the try statement completes abruptly for reason R.
    • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).

(my italics). A return is one kind of "abrupt completion", in other words the return from the finally overrules the one from inside the try.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
1

It returns true because whenever a finally block completes abruptly, either by return-ing or by throwing an exception, that completion supersedes any previous return-value or exception. (See §14.20.2 "Execution of try-finally and try-catch-finally" in the Java Language Specification, Java SE 7 Edition.)

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • [JLS spec](http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2) - "If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S." – Russell Zahniser Jun 26 '13 at 15:00
  • @RussellZahniser: Yup, you commented just as I was adding the link. (But note that that specific sentence is not actually the one that applies in this case. There's a separate, similar sentence for this case.) – ruakh Jun 26 '13 at 15:02
1

Because no matter what happens in the try catch portion, the finally block will always do what you ask so in this case it returns true. Just remove the finally statement and it should return false.

Chris
  • 39
  • 1
  • 2
  • 10
0

Finally block doesnot execute when try or catch block terminate by calling System.exit function. Similarly if the thread executing try catch dies while executing try or catch block then finally block may not execute.

So its likely that your try catch finally block will almost always return true even if your try block is returning false .

Smrita
  • 1,259
  • 3
  • 18
  • 38
-1

Because the finally block will always be executed if a return is encountered.