没有编译器错误的多个返回语句 [英] Multiple return statements without compiler error

查看:30
本文介绍了没有编译器错误的多个返回语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个面试问题:

public class Demo {

    public static void main(String[] args) {
        System.out.println(foo());
    }

    static String foo() {
        try {
            return "try ...";
        } catch (Exception e) {
            return "catch ...";
        } finally {
            return "finally ..."; //got as result
        }
    }
}

我的问题是为什么没有编译时错误.当我的 finally 块中有 return 语句时,它必然会从 finally 而不是 trycatch 返回> 阻止.我试图用 -Xlint 选项编译这段代码,它给出了一个警告.

My question is why there are no compile time errors. When I have the return statement in my finally block, it is bound to return from finally instead of try and catch block. I tried to compile this code with -Xlint option, it gives a warning as.

warning: [finally] finally clause cannot complete normally

推荐答案

它不会给出编译错误,因为 Java 语言规范允许这样做.但是,它会发出警告消息,因为在 finally 块中包含 return 语句通常是个坏主意.

It does not give a compilation error because it is allowed by the Java Language Specification. However, it gives a warning message because including a return statement in the finally block is usually a bad idea.

您的示例中发生的情况如下.try 块中的 return 语句被执行.但是,必须始终执行 finally 块,以便在 catch 块完成后执行它.出现在那里的 return 语句覆盖了前一个 return 语句的结果,因此该方法返回第二个结果.

What happens in your example is the following. The return statement in the try block is executed. However, the finally block must always be executed so it is executed after the catch block finishes. The return statement occurring there overwrites the result of the previous return statement, and so the method returns the second result.

类似地,finally 块通常不应该抛出异常.这就是为什么警告说 finally 块应该正常完成,即没有 return 或抛出异常.

Similarly a finally block usually should not throw an exception. That's why the warning says that the finally block should complete normally, that is, without return or throwing an exception.

这篇关于没有编译器错误的多个返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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