62

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)...

3
  • 4
    why! o why! writing a code which your fellow programmer hate you for?!
    – Nishant
    Jan 31, 2012 at 10:43
  • 7
    @Nishant: I often use if (2 > 1) return; for debugging purposes. Jan 31, 2012 at 11:37
  • 9
    @Nishant It's just for debugging, I don't leave chunks of code lying around unless I directly work with them. Jan 31, 2012 at 11:48

5 Answers 5

115

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.

2
  • 21
    You can replace if (1==1) with if (true) since 1==1 is always true.
    – Steve Kuo
    Jan 31, 2012 at 16:57
  • 3
    coming 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
4
33. if (1==1) return;
34. System.out.println("Hello world!");

It works in other languages too. But ByteCode without row 34.

1
  • 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.
    – alife
    Feb 16, 2022 at 1:24
3

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?

0

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

-12

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.