Java中的编译器意外地抱怨“缺少return语句". [英] The compiler in Java complains unexpectedly about "missing return statement"

查看:110
本文介绍了Java中的编译器意外地抱怨“缺少return语句".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下方法即使具有显式的返回类型int,也不会使用return语句.

The following methods go without return statements even though they have an explicit return type int.

public int foo1()
{
    while(true) {}
}

public int foo2()
{
    for(;;);
}

public int foo3()
{
    while(true)
    {
        if(true)
        {
            //... Stuff
        }
    }
}


上述所有方法即使不包含return语句,也不会发出编译器错误.可能是因为它们都是无限循环,永远不会返回,因此,编译器可能会忽略return语句.如果是这样,那么以下情况也很明显.


All of the above methods issue no compiler error even though they contain no return statement. It may be because they all are infinite loops that will never return and hence, the compiler may ignore the return statement. If it is so, then the following case is also obvious.

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



在上述方法中,即使if条件始终为 true ,编译器仍会抱怨缺少return语句,因此return语句显然将返回指定值.要抑制此错误,需要在else块之内或其他情况下使用另一个return语句.

其背后是否有某些特定原因?前面的情况不是C#可以按预期运行的那样.



In the preceding method, the compiler complains about missing return statement even though the if condition is always true and consequently, the return statement is obviously going to return the specified value. Suppressing this error requires another return statement within an else block or otherwise.

Are there some specific reasons behind it? The preceding is not the case with C# that works perfectly as expected.

推荐答案

我找到了一些有趣的信息,这些信息与您在这里观察到的现象有关:<一个href ="http://stackoverflow.com/questions/8863676/compiler-complains-about-missing-return-statement-even-though-it-is-impossible">即使没有可能,编译器也会抱怨缺少return语句 [ ^ ].该讨论中有一个很好的链接,指向 Java语言规范 [ ^ ]: 声明14.21 [^ ] .在上述此处的末尾有一些内容href ="http://java.sun.com/docs/books/jls/third_edition/html/statements.html#236554" target ="_ blank" title =新窗口"> ^ ].

问候,

曼弗雷德(Manfred)
I''ve found some interesting information about the phenomenon you''ve observed here: Compiler complains about missing return statement even though it is impossible[^]. There is a great link in that discussion that points to the Java Language Specification[^]: Statements 14.21[^]. With some titbits at the end of above mentioned section here[^].

Regards,

Manfred


上面的示例很垃圾-但也永远不会结束循环.这也可能导致编译器警告(也出错?).添加break条件时,也会由于返回值而导致错误.

示例foo4()永远不会持久.因此,它需要返回"something":

The above examples are pretty much rubbish - but also never ending loops. That can also cause a compiler warning (also error?). You will also get the error due to the return value when you add a break condition.

The example foo4() is not ever lasting. Therefor it needs to return "something":

public int foo4() {
    if(true){ return(5); }
    return -1; // invalid int value
}


这篇关于Java中的编译器意外地抱怨“缺少return语句".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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