如果 finally 块修改了从 catch 块返回的值,会发生什么? [英] What happens if a finally block modifies the value returned from a catch block?

查看:44
本文介绍了如果 finally 块修改了从 catch 块返回的值,会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当变量 value 是原语时,变量的 finally 块修改不起作用.但是,当 value 是引用时,变量的 finally 块修改生效.你能帮忙解释一下为什么会这样吗?

When the variable value is a primitive the finally block modification of the variable has no effect. However when value is an reference the finally block modification of the variable takes effect. Can you please help why this happens?

StringBuilder value = new StringBuilder("abc");

StringBuilder get() {

    try {
        throw new IndexOutOfBoundsException();
    } catch (IndexOutOfBoundsException e) {
        return value;
    } finally {
        value = value.append("def");
    }
}

<小时>

 int value = 10;

int get() {

    try {
        throw new IndexOutOfBoundsException();
    } catch (IndexOutOfBoundsException e) {
        return value;
    } finally {
        value = value + 10;
    }
}

推荐答案

对于所有不可变对象和原语,您将得到相同的答案.所有可变对象都将返回更改后"的值,而所有不可变对象将保留其原始值,因此最终没有任何影响.

You will get the same answer for all immutable objects and primitives. All mutable objects will return the "changed" value whereas all immutable objects will retain their original value, thus finally do not have any effect.

这篇关于如果 finally 块修改了从 catch 块返回的值,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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