【问题标题】:The order of return value with try catch finallytry catch finally 的返回值顺序
【发布时间】:2021-05-30 16:05:00
【问题描述】:

我用这段代码来测试try catch finally:

public class My{
    public static void main(String[] args) {
        System.out.println(fun1());
        System.out.println(fun2());
    }

    public static int fun1() {
        int a = 1;
        try {
            System.out.println(a / 0);
            a = 2;
        } catch (ArithmeticException e) {
            a = 3;
            return a;
        } finally {
            a = 4;
        }
        return a;

    }

    public static int fun2() {
        int a = 1;
        try {
            System.out.println(a / 0);
            a = 2;
        } catch (ArithmeticException e) {
            a = 3;
            return a;
        } finally {
            a = 4;
            return a;
        }

    }
}

输出:

3
4

我知道 finally 会一直运行。我想这两个函数的结果应该是4,但实际上fun1()是3,fun2()是4。为什么?

【问题讨论】:

标签: java exception try-catch try-catch-finally


【解决方案1】:

这个问题密切相关,虽然它返回文字而不是变量:Multiple returns: Which one sets the final return value?

fun1 中,返回值是通过catch 块中的return a 设置的。在该行,a 的值被复制到返回值中。稍后更改a 不会更改返回值。

fun2 中,finally 块中有显式返回,因此 finally 块中的返回值就是返回的值。

请仔细阅读上述问题中的答案,了解为什么不应该编写这样的代码。

另一个相关的问题是这个:Returning from a finally block in Java

【讨论】:

  • 这很有帮助。
【解决方案2】:

简单来说,当一个函数返回一些东西时,它会从最后执行的 return 语句中返回。在fun2() 中,第一个返回值是3,它被finally 块的返回值覆盖,即4。而在fun1() 方法中,返回从catch 块设置为3,并且由于func1() 的最后一行永远不会被执行,因此返回3

【讨论】:

    猜你喜欢
    • 2014-04-27
    • 2018-11-05
    • 2014-12-26
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 2013-06-28
    • 2011-11-04
    相关资源
    最近更新 更多