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

Martin Melka
  • 7,177
  • 16
  • 79
  • 138

5 Answers5

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.

Thomas Vos
  • 12,271
  • 5
  • 33
  • 71
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • 21
    You can replace `if (1==1)` with `if (true)` since 1==1 is always true. – Steve Kuo Jan 31 '12 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 – 463035818_is_not_an_ai May 16 '18 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.

Dmytro Sokolyuk
  • 966
  • 13
  • 13
  • 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 '22 at 01: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?

Community
  • 1
  • 1
Dawood
  • 5,106
  • 4
  • 23
  • 27
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

csharpfolk
  • 4,124
  • 25
  • 31
-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.

Balaswamy Vaddeman
  • 8,360
  • 3
  • 30
  • 40