Java: How to @SuppressWarnings unreachable code?

匆匆过客 提交于 2019-12-19 15:26:32

问题


Sometimes when you are debugging, you have unreachable code fragment. Is there anyway to suppress the warning?


回答1:


The only way to do this on any compiler is @SuppressWarnings("all").

If you're using Eclipse, try @SuppressWarnings("unused").




回答2:


Java has (primitive) support for debugging like this in that simple if on boolean constants will not generate such warnings (and, indeed when the evaluation is false the compiler will remove the entire conditioned block). So you can do:

if(false) {
    // code you don't want to run
    }

Likewise, if you are temporarily inserting an early termination for debugging, you might do it like so:

if(true) { return blah; }

or

if(true) { throw new RuntimeException("Blow Up!"); }

And note that the Java specification explicitly declares that constantly false conditional blocks are removed at compile time, and IIRC, constantly true ones have the condition removed. This includes such as:

public class Debug
{
static public final boolean ON=false;
}

...

if(Debug.ON) {
    ...
    }



回答3:


As Cletus tells us,

It depends on your IDE or compiler.

That said, at least for Eclipse, there is not a way to do this. With my Eclipse configuration, unreachable code causes a compile-time error, not just a warning. Also note this is different from "dead code," e.g.

if (false)
{
    // dead code here
}

for which Eclipse (by default) emits a warning, not an error.




回答4:


According to the Java Language Specification:

It is a compile-time error if a statement cannot be executed because it is unreachable.

You can sometimes turn unreachable code into dead code (e.g., the body of if (false) {...}). But it being an error is part of the language definition.



来源:https://stackoverflow.com/questions/6025340/java-how-to-suppresswarnings-unreachable-code

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