[英]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节
(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
是一种“突然完成”,换句话说, finally
的return
否决了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-finally
和try-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.