编译器抱怨“缺少退货声明”即使不可能达到返回陈述将丢失的条件 [英] Compiler complains about "missing return statement" even though it is impossible to reach condition where return statement would be missing

查看:122
本文介绍了编译器抱怨“缺少退货声明”即使不可能达到返回陈述将丢失的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的方法中,编译器抱怨缺少return语句,即使该方法只有一条路径,并且它包含 return 声明。抑制错误需要另一个 return 语句。

In the following method, the compiler complains about a missing return statement even though there is only a single path through the method, and it contains a return statement. Suppressing the error requires another return statement.

public int foo() {
    if (true) {
        return 5;
    }
}

鉴于 Java编译器可以识别无限循环,为什么它也不能处理这种情况呢?链接的问题提示,但不提供此特定情况的详细信息。

Given that the Java compiler can recognize infinite loops, why doesn't it handle this situation as well? The linked question hints, but doesn't provide details for this specific case.

推荐答案

JLS 14.21,无法访问的语句是处理此问题的部分:

JLS 14.21, Unreachable Statements is the section that deals with this:


if语句,无论是否有else部分,都以不寻常的方式处理。出于这个原因,本节末尾将单独讨论。

The if statement, whether or not it has an else part, is handled in an unusual manner. For this reason, it is discussed separately at the end of this section.

最终它与处理条件编译的方式有关。考虑这种方法:

Ultimately it has to do with how conditional compilation is handled. Consider this method:

public int foo() {
    if (DEBUG) {
        return 5;
    }
}

如果 DEBUG static final boolean true; 你可能认为编译器应该足够智能,以实现该方法将始终返回 5 。但如果它被更改为 false ,则代码不再有效。

If DEBUG is static final boolean true; you might think the compiler should be smart enough to realize the method will always return 5. But if it's changed to false, the code is no longer valid.

该方法必须对所有路径有效通过方法没有源代码更改,允许优化编译器省略字节码而无需源代码修改,无论标志值如何。

The method must be valid for all paths through the method without a source code change, allowing optimizing compilers to omit bytecode without source modifications regardless of the flag's value.

链接JLS部分的最后详细介绍。

这篇关于编译器抱怨“缺少退货声明”即使不可能达到返回陈述将丢失的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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