Java Compiler: Stop complaining about dead code

自作多情 提交于 2019-12-05 03:19:35
Joachim Sauer

There are no flags to turn of this behaviour. The rules that make dead code a compile time error are part of the JLS (§14.21 Unreachable Statements) and can't be turned off.

There's an explicit loophole in the loop which allows code like this:

if (true) return;

someOtherCode(); // this code will never execute, but the compiler will still allow it

This is done explicitly to allow "commenting-out" or conditional compilation (depending on some static final boolean flag).

In case you're curious: the loophole is based on the fact that a known-constant value of the condition expression of an if statement is not considered when checking reachability of code within or after the if statement. A similar situation occurs with while, where known-constant values are considered, so this code will not compile:

while (true) return;

someOtherCode(); // this will be flagged as an unreachable statement

You shouldn't have lots of dead cod ein your project however two ways I get around this for prototyping.

Use /* */ to comment out the code.

    // But, of course, I don't want to start the whole project, so:
    /*
    // The real project starts here...


    */
}

or create a second method.

    // But, of course, I don't want to start the whole project, so:
    // realProject();
}

public static void realProject()
    // The real project starts here...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!