Java的返回值在try-catch-finally机制 [英] Java's return value in try-catch-finally mechanism

查看:172
本文介绍了Java的返回值在try-catch-finally机制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚遇到以下代码:

public class TestFinally {
    public static void main(String[] args) {
        int returnValue = function();

        System.out.println("Return value: " + returnValue);
    }

    public static int function() {
        try {
            return 1;
        } catch (Exception e){
            return 2;
        } finally{
            return 3;
        }
    }
}

毫无疑问,运行此代码将产生返回值:3的输出。

It is without a doubt that running this code will yield an output of "Return value: 3".

但是,我很好奇:


  1. 内脏的机制在JVM中。有人知道VM是否真的通过覆盖第一个return 1来替换堆栈上的返回值?如果是这样,我可以在哪里找到更多的信息。

  2. 我还没有找到用于返回的finally机制,这是使用这种方式,允许在实现的
    在JVM中。如果这个代码结构被用作返回
    错误代码的手段,那么在我看来,有更好的方法来记录错误
    或返回这些错误代码。有没有人发现这种
    结构的用途?

非常感谢。

干脆,
Vern

Cheers, Vern

推荐答案

我在Java语言规范中发现,你的代码片段应该返回3.当然,它没有提到JVM应该如何实现这一点,以及可以做什么可能的优化。

What I found in the Java language specification at least defines that your code snippet should return 3. Of course, it does not mention how the JVM should implement this, and what possible optimizations one could do.

14.20.2 定义


如果try块的执行突然由于任何其他原因R而完成,则执行finally块。然后有一个选择:

If execution of the try block completes abruptly for any other reason R, then the finally block is executed. Then there is a choice:


  1. 如果finally块正常完成,则try语句突然完成原因R。

  2. 如果finally块突然因原因S完成,那么try语句会突然地因为原因S而完成(并且丢弃原因R)。


并且第14章的开头( Section 14.1 更精确)指定正常和突然完成是什么。例如,具有给定值的 return 是突然完成。

And the start of chapter14 (section 14.1 to be more precise) specifies what a normal and abrupt completion is. For example a return with a given value is an abrupt completion.

因此,在这种情况下, finally 块突然完成(原因: return 有一个给定的值),因此 try 将突然完成相同的原因(并返回3)。这在第14.17节中关于return语句以及



Hence in this case, the finally block completes abruptly (reason: return with a given value), so the try will complete abruptly for the same reason (and return 3). This is confirmed in section 14.17 about the return statement as well


如果Expression的求值正常完成,产生一个值V,则返回语句突然完成,原因是返回值为V.

If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V.

这篇关于Java的返回值在try-catch-finally机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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