java:尝试finally块执行 [英] java: try finally blocks execution

查看:183
本文介绍了java:尝试finally块执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当try块中存在 return; 时,我对try-finally执行感到困惑。根据我的理解,将始终执行finally块,即在返回调用方法之前。在考虑以下简单代码时:

I am confused about the try-finally execution when there exists return; in the try block. In my understanding, the finally block will always be executed, i.e. before returning to the calling method. While considering the following simple code:

public class TryCatchTest {
    public static void main(String[] args){
        System.out.println(test());
    }
    static int test(){
        int x = 1;
        try{
            return x;
        }
        finally{
            x = x + 1;
        }
    }
}

打印结果实际为1这是否意味着finally块未执行?任何人都可以帮我吗?

The result printed is actually 1. Does this mean the finally block is not executed? Can anyone help me with it?

推荐答案

当你从返回时尝试 block,返回值存储在该方法的堆栈帧中。之后执行finally块。

When you return from try block, the return value is stored on the stack frame for that method. After that the finally block is executed.

更改finally块中的值不会更改堆栈上已有的值。但是,如果再次从finally块返回,则将覆盖堆栈上的返回值,并返回新的 x

Changing the value in the finally block will not change the value already on the stack. However if you return again from the finally block, the return value on the stack will be overwritten, and the new x will be returned.

如果在finally块中打印 x 的值,您将知道它已执行,并且的值x 将被打印。

If you print the value of x in finally block, you will get to know that it is executed, and the value of x will get printed.

static int test(){
    int x = 1;
    try{
        return x;
    }
    finally{
        x = x + 1;
        System.out.println(x);  // Prints new value of x
    }
}






注意:如果返回引用值,引用值将存储在堆栈中。在这种情况下,您可以使用该引用更改object的值。


Note: In case of a reference value being returned, the value of reference is stored on the stack. In that case, you can change the value of object, using that reference.

StringBuilder builder = new StringBuilder("");
try {
    builder.append("Rohit ");
    return builder;

} finally {
    // Here you are changing the object pointed to by the reference
    builder.append("Jain");  // Return value will be `Rohit Jain`

    // However this will not nullify the return value. 
    // The value returned will still be `Rohit Jain`
    builder =  null;
}

建议阅读:

  • JVM Specs - Frames

这篇关于java:尝试finally块执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆