简体   繁体   中英

Java try- catch- finally block

If I run the following code:

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

why does it return true ?

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 .

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 .)

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.

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 .

因为如果遇到返回,finally块将始终执行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM