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

查看:26
本文介绍了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中的内部机制.有谁知道虚拟机是否真的通过覆盖第一个return 1"来替换堆栈上的返回值?如果是这样,我在哪里可以找到这方面的更多信息.
  2. 我还没有找到以这种方式使用并允许在已实现的 finally 机制中返回的用途在JVM中.如果将此代码构造用作返回的手段错误代码,我认为有更好的方法来记录错误或返回这些错误代码.有没有人发现这样的用途构造?

非常感谢.

干杯,维恩

推荐答案

我在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 块正常完成,则由于原因 R,try 语句会突然完成.
  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

如果表达式的计算正常完成,产生一个值 V,那么 return 语句突然完成,原因是一个返回值 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天全站免登陆