Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler complains about "missing return statement" even though it is impossible to reach condition where return statement would be missing

Tags:

java

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;     } } 

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.

like image 588
Lion Avatar asked Jan 14 '12 16:01

Lion


People also ask

How do I fix missing return statement error?

In order to solve the missing return statement error, we simply need to add the return statement to the method just like to the one we did in case one. So, we will return the some value of the same type which we used before the name like as: public static String checkNumber( int number) { //initialize variable i.

What does a function return when it is missing a return statement?

Code Inspection: Missing return statement The foo function must return the integer value but the function body returns nothing. To fix the error, add a RETURN statement (for example, return 1; ).

What type of error is a missing return statement?

The missing return statement error is a compile-time error. Therefore this type of error tends to be easy to detect. The main causes are: a return statement was simply omitted by mistake. the method doesn't return any value, but type void is not declared in the method signature.

What happens when a return statement in a method is reached?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.


1 Answers

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

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;     } } 

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.

The very end of the linked JLS section goes in to significant detail.

like image 119
Dave Newton Avatar answered Oct 13 '22 18:10

Dave Newton