奇怪的是最后的行为? [英] Strange finally behaviour?

查看:114
本文介绍了奇怪的是最后的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Test2 {

    public static void main(String[] args) {
        Test2 obj=new Test2();
        String a=obj.go();

        System.out.print(a);
    }


    public String go() {
        String q="hii";
        try {
            return q;
        }
        finally {
            q="hello";
            System.out.println("finally value of q is "+q);
        }
    }

为什么打印 hii 从函数 go()返回后,finally块中的值已更改为hello?

Why is this printing hii after returning from the function go(), the value has changed to "hello" in the finally block?

该程序的输出是

finally value of q is hello
hii


推荐答案

那是因为你返回了一个从<$ c评估的值在您更改finally块中的 q 的值之前,$ c> q 。您返回 q ,评估其值;然后你在 finally 块中更改了 q ,这不会影响加载的值;然后使用评估值完成返回。

That's because you returned a value that was evaluated from q before you changed the value of q in the finally block. You returned q, which evaluated its value; then you changed q in the finally block, which didn't affect the loaded value; then the return completed, using the evaluated value.

不要写这样棘手的代码。如果它让那个写它的人感到困惑,想象一下它会引起下一个人的问题,几年后你会在其他地方走下去。

Don't write tricky code like this. If it confuses the guy who wrote it, imagine the problems it will cause the next guy, a few years down the track when you are somewhere else.

这篇关于奇怪的是最后的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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