Java try-catch-finally 之后返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22533128/
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-08-13 16:18:36  来源:igfitidea点击:

try-catch-finally with return after it

javareturntry-catchtry-catch-finallyfinally

提问by Kevin Cruijssen

I know how try, catch & finally work (for most part), but I have one thing I was wondering: what happens with a return statement after a try-catch-finally, while we already had a return in the try (or catch)?

我知道 try、catch 和 finally 是如何工作的(在大多数情况下),但我想知道一件事:try-catch-finally 之后的 return 语句会发生什么,而我们已经在 try(或 catch)中返回了)?

For example:

例如:

public boolean someMethod(){
    boolean finished = false;
    try{
        // do something
        return true;
    }
    catch(someException e){
        // do something
    }
    finally{
        // do something
    }
    return finished;
}

Let's say nothing went wrong in the try, so we returned true. Then we will go to the finally where we do something like closing a connection, and then?

假设在 try 中没有任何问题,所以我们返回 true。然后我们将转到finally,在那里我们执行诸如关闭连接之类的操作,然后呢?

Will the method stop after we did some stuff in the finally (so the method returned true in the try), or will the method continue after the finally again, resulting in returning finished(which is false)?

我们在finally中做了一些事情后,该方法会停止(因此该方法在try中返回true),还是在finally之后该方法会继续运行,导致返回finished(这是false)?

Thanks in advance for the responses.

预先感谢您的答复。

采纳答案by Joffrey

The fact that the finally block is executed does not make the program forget you returned. If everything goes well, the code after the finally block won't be executed.

执行 finally 块的事实不会使程序忘记您返回。如果一切顺利,finally 块之后的代码将不会被执行。

Here is an example that makes it clear:

这里有一个例子,说明很清楚:

public class Main {

    public static void main(String[] args) {
        System.out.println("Normal: " + testNormal());
        System.out.println("Exception: " + testException());
    }

    public static int testNormal() {
        try {
            // no exception
            return 0;
        } catch (Exception e) {
            System.out.println("[normal] Exception caught");
        } finally {
            System.out.println("[normal] Finally");
        }
        System.out.println("[normal] Rest of code");
        return -1;
    }

    public static int testException() {
        try {
            throw new Exception();
        } catch (Exception e) {
            System.out.println("[except] Exception caught");
        } finally {
            System.out.println("[except] Finally");
        }
        System.out.println("[except] Rest of code");
        return -1;
    }

}

Output:

输出:

[normal] Finally
Normal: 0
[except] Exception caught
[except] Finally
[except] Rest of code
Exception: -1

回答by Christophe Roussy

In that case the code inside the finally is run but the other return is skipped when there are no exceptions. You may also see this for yourself by logging something :)

在这种情况下,finally 中的代码会运行,但在没有异常时会跳过另一个 return。你也可以通过记录一些东西来亲眼看到这一点:)

Also see this concerning System.exit: How does Java's System.exit() work with try/catch/finally blocks?

另请参阅以下内容System.exitJava 的 System.exit() 如何与 try/catch/finally 块一起工作?

And see returning from a finally: Returning from a finally block in Java

并查看从 finally返回从 Java 中的 finally 块返回

回答by Dhanush Gopinath

If all goes well, return inside the tryis executed after executing the finallyblock.

如果一切顺利,try则在执行完finally块后返回内部执行。

If something goes wrong inside try, exceptionis caught and executed and then finallyblock is executed and then the return after that is executed.

如果内部出现问题tryexception则被捕获并执行,然后finally执行块,然后执行之后的返回。

回答by Narendra11744

Definitely the code inside try will execute.. but when it reaches to return statement.. it will move to the finally block without executing the return statement in try block.. and then the code of finally will be executed and then the return statement of try will execute.

肯定try里面的代码会执行..但是当它到达return语句..它会移动到finally块而不执行try块中的return语句..然后finally的代码将被执行,然后是return语句尝试将执行。

回答by CoderCroc

public int Demo1()
    {
        try{
            System.out.println("TRY");
            throw new Exception();
            }catch(Exception e){
                System.out.println("CATCH");
            }finally{
                System.out.println("FINALLY");
            }return 0;

    }

the output of call to this method is like this

调用这个方法的输出是这样的

TRY
CATCH
FINALLY
0

Means Consider Try{}catch{}finally{}as sequence of statements executed one by one In this particular case. And than control goes to return.

手段考虑Try{}catch{}finally{}的语句序列执行逐个在这种特殊情况下。然后控制权返回。