Java - 如果我在 catch 块中返回,是否会执行 finally 块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17980172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 19:45:27  来源:igfitidea点击:

Java - If I return in a catch block, will the finally block be executed?

javascopetry-catch-finally

提问by Comic Sans MS Lover

This is what I'm trying to do:

这就是我想要做的:

try {

    //code
} catch (Exception e) {

    return false;
} finally {

    //close resources
}

Will this work? Is it bad practice? Would it be better doing this:

这会奏效吗?这是不好的做法吗?这样做会不会更好:

boolean inserted = true;

try {

    //code
} catch (Exception e) {

    inserted = false;
} finally {

    //close resources
}

return inserted;

回答by JB Nizet

Yes, it will. The only things that can prevent a finally block to execute (AFAIR) are System.exit(), and an infinite loop (and a JVM crash, of course).

是的,它会的。唯一可以阻止 finally 块执行 (AFAIR) 的是System.exit(), 和无限循环(当然还有 JVM 崩溃)。

回答by Marko Topolnik

The finallyblock is executed always, unconditionally, as the last thing the try-catch-finallyblock does. Even if you execute Thread#stopagainst it, the finallyblock will still execute, just as if a regular exception ocurred.

finally块被执行总是无条件地,因为过去的事情try-catch-finally块呢。即使您Thread#stop针对它执行,该finally块仍会执行,就像发生了常规异常一样。

Not just that, if you return from finally, that return value will trample over the return from either tryor catch.

不仅如此,如果您从 返回finally,该返回值将践踏来自try或 的返回值catch

BTW Your first example is not just fine, but preferred. In the second example the reader must chase around the assignments to the variable, which is a tedious job and lets bugs slip through very easily.

顺便说一句,你的第一个例子不仅很好,而且是首选。在第二个示例中,读者必须追逐变量的赋值,这是一项乏味的工作,并且很容易让错误溜走。

回答by Eng.Fouad

Both are approximately the same. However, be careful with the following case:

两者大致相同。但是,请注意以下情况:

int i = 0;

try
{
    //code
}
catch(Exception e)
{
    return i;
}
finally
{
    i = 1;
}

0is what will be returned.

0是什么将被返回。

回答by Petr Pudlák

I just wanted to add that it's described in the specs:

我只是想补充一点,它在规范中有所描述:

If the catch block completes abruptly for reason R, then the finally block is executed.

如果 catch 块由于原因 R 突然完成,则执行 finally 块。

where of course

当然在哪里

It can be seen, then, that a return statement always completes abruptly.

可以看出,return 语句总是突然完成。