Unreachable code error vs. dead code warning in Java under Eclipse?

后端 未结 8 1447
眼角桃花
眼角桃花 2020-11-28 06:59

Does anyone know why:

public void foo()
{
    System.out.println(\"Hello\");
    return;
    System.out.println(\"World!\");
}

Would be rep

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 07:22

    I think one way to some it up is that unreachable code is most likely a mistake, and the JLS tries to protect you from such mistakes.

    Allowing if (true) return; is a good way to work around the JLS limitation if you actually want to do this on purpose. If the JLS stopped this, it would be getting in the way. In addition, it should also stop:

     public static boolean DEBUG = true; //In some global class somewhere else
    
    
     ...
    
     if (DEBUG) return; //in a completely unrelated class.
    
     ...
    

    Because the DEBUG constant is completely in-lined, and functionally equivalent to just typing a true in that if condition. From a JLS perspective those two cases are very similar.

提交回复
热议问题