简体   繁体   English

Java try-catch-finally块

[英]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 ? 为什么返回true

From the Java Language Specification section 14.20.2 摘自Java Language Specification第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: 如果由于任何其他原因R导致try块的执行突然完成,则执行finally块,然后可以选择:
    • If the finally block completes normally, then the try statement completes abruptly for reason R. 如果finally块正常完成,则try语句由于原因R突然完成。
    • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded) . 如果final块由于原因S突然完成,则try语句由于原因S突然完成(并且原因R被丢弃)

(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 . return是一种“突然完成”,换句话说, finallyreturn否决了try内部的return

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. 之所以返回true是因为无论何时finally块通过return -ing或引发异常而突然完成,该完成都会取代以前的任何返回值或异常。 (See §14.20.2 "Execution of try-finally and try-catch-finally " in the Java Language Specification , Java SE 7 Edition .) (请参见Java SE 7版Java语言规范中的第14.20.2节“ try-finallytry-catch-finally 。)

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. 因为无论在try catch部分发生什么,finally块都将始终按照您的要求进行操作,因此在这种情况下它将返回true。 Just remove the finally statement and it should return false. 只需删除finally语句,它应该返回false。

Finally block doesnot execute when try or catch block terminate by calling System.exit function. 当try或catch块通过调用System.exit函数终止时, System.exit块不执行。 Similarly if the thread executing try catch dies while executing try or catch block then finally block may not execute. 类似地,如果执行try catch的线程在执行try或catch块时死亡,那么finally块可能不会执行。

So its likely that your try catch finally block will almost always return true even if your try block is returning false . 因此,即使try块返回false,您的try catch finally块也几乎总是返回true。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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