How to unconditionally exit / return the void method?

void A() {
  B();

  // return; <- compiler error "unreachable code"

  if (true) return; // <- this works

  // code that I will test later
  ...
  C(); 
  D();
}

Here is what I am doing now. Is there a simple " exit;" or " return;" that will not give an error "unreachable code"without using if?


Just to make it clear: it if (true) return; works (with the warning "Dead code", which I do not like and can suppress)!
if I just use return; only then I get an error "unreachable code".

Note. The simple “This cannot be done without use if” is also an acceptable answer provided by the link.

+4
source share
4 answers

, Java , . ( , Java , , JVM .)

+5

, :

if (true) return;

, . real, .

, , .

+5

?

void A() {
  B();

  /* code that I will test later
  C(); 
  D();
  */
}
+1

if (true) return;

This statement gives an unattainable code error, because the compiler knows that this block ifwill be executed exactly (as you set the condition true). Your block ifcontains an operator return, which means in the instructions below it will not be executed. Therefore, you get an error "unreachable code".

0
source

All Articles