Why does this code have a missing return statement error?

前端 未结 6 967
情话喂你
情话喂你 2020-12-21 00:50

If I change the else if portion of this code to an else statement it runs without any problems so I get how to make it run. What I\'m a little confused about is why I get a

6条回答
  •  时光取名叫无心
    2020-12-21 01:21

    Other questions have explained what the error message means from an intuitive perspective. However the "The compiler is smart, but not perfect!" comment is missing the point.

    In fact, the Java compiler is calling your example an error because the Java Language Specification requires it to call it an error. The Java compiler is not permitted to be "smart" about this.


    Here is what the JLS (for Java 71) actually says, and how it applies to a simplified version of the incorrect example, and then a corrected version.

    "If a method is declared to have a return type, then a compile-time error occurs if the body of the method can complete normally (JLS 14.1). In other words, a method with a return type must return only by using a return statement that provides a value return; it is not allowed to "drop off the end of its body". " - JLS 8.4.7

    (Read JLS 14.1 for the definition of "normal completion" ...)

    And the rules for deciding whether a "normal" completion is possible are the reachability rules in JLS 14.21. And they say:

    1. "An if-then statement can complete normally iff it is reachable."
    2. "An if-then-else statement can complete normally iff the then-statement can complete normally or the else-statement can complete normally."
    3. "A break, continue, return, or throw statement cannot complete normally."

    (Where 'iff' means "if and only if" ...)

    Consider a simplified version of the example:

       public int test(boolean a) {
          if (a) {
            return 1;
          }
          else if (!a) {
            return 0;
          }
       }
    

    In this example, the else-statement is an if-then which can complete normally by rule #1. Therefore, by rule #2, the if-then-else statement can also complete normally. But that is a compilation error, because JLS 8.4.7 says that a method with a return type cannot complete normally.

    But if you change the example to this ...

      public int test(boolean a) {
          if (a) {
            return 1;
          }
          else {
            return 0;
          }
      }
    

    Now by rule #3, both the if-statement and the else-statement cannot complete normally. So by rule #2, the entire if-then-else cannot complete normally. That is what it required by JLS 8.4.7 ... therefore no compilation error.

    1 - The Java 8 JLS will say essentially the same thing, though the section numbers may be different ...

提交回复
热议问题