Is it possible to somehow ignore this error? I find it much easier to just put return
in front of the code I don't want to run than to comment it (when the comments overlap and behave badly)...
5 Answers
No. It's a compile time error. So you must get rid of it before running your class.
What I usually do is put a fake if
statement in front of it. Something like:
if(true)
return;
// unwanted code follows. no errors.
i++;
j++;
With this code, you will not get a Unreachable statement
error. And you will get what you want.
-
21You can replace
if (1==1)
withif (true)
since 1==1 is always true. Jan 31, 2012 at 16:57 -
3coming from c++ it feels a bit odd how java tries to protect you and holds your hand and then sometimes pulls you in the wrong direction. Nice workaround, it also has the advantage that anyhow a
if (true)
signals that there is something fishy going on and the danger of removing it later is a bit reduced May 16, 2018 at 11:38
33. if (1==1) return;
34. System.out.println("Hello world!");
It works in other languages too. But ByteCode without row 34.
-
Javac seems to be fine with
if (true)...
. The compiler will still remove the conditional as a builtin base level optimization, but will not trigger an Unreachable Code error.– alifeFeb 16, 2022 at 1:24
It isn't possible to ignore this error since it is an error according to the Java Language Specification.
You might also want to look at this post: Unreachable code error vs. dead code warning in Java under Eclipse?
If you want disable/enable certain piece of code many times trick from old C may help you:
some_code();
more_code();
// */
/*
some_code();
more_code();
// */
Now you need only to write /*
at the beginning
you have to fix that unreachable code.
public void display(){
return; //move the return statement to appropriate place
int i;
}
compiler will not compile your source code. you have to take care of your source code that every line is reachable to compiler.
if (2 > 1) return;
for debugging purposes.