DesirePRG DesirePRG - 1 month ago 6
Java Question

why intellij complains to add a return to an unreachable statement

My IDE keeps complaining to add a "retrun" statement in hello() method after the catch block. Isn't that return statement unreachable? so why should i include that?

import java.sql.SQLException;

public class Test {
public static void main(String[] args) {
hello();
}


public static boolean hello() {

try{
hello2();
} catch(SQLException e){
handleException();
}
return false;
}

public static String hello2() throws SQLException {
throw new SQLException("");
}

public static void handleException(){
throw new RuntimeException();
}
}

Answer

Isn't that return statement unreachable?

According to the rules that the JLS specifies for determining that a statement is reachable, the return false; statement is reachable. (Refer to JLS 14.21 for the full details.)

The rules do not take account of the behavior of a separate method. They make the assumption that any method call may return, no matter how the method is actually implemented.

The JLS's assumption is essential in the case where the method is in a separate compilation unit. (Consider the case where the called method is changed and recompiled without recompiling the calling method.)

It is also essential in the case where the logic of the method is complicated. There will be cases where it would be impossible for a compiler to be sure whether a method can terminate; c.f. the Halting Problem. It would be a bad thing for the "correctness" of a Java program to depends on the ability of the compiler determine if an arbitrary method call could return or not. The simple solution (adopted by the JLS) is the compiler should not even try to do that ... for the purposes of reachability checking.

Comments