Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unconditionally exit/return a void method?

Tags:

java

return

void A() {
  B();

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

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

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

This is what I do now. Is there a simple "exit;" or "return;" that will not yield "unreachable code" error without using the if?


Just to make it clear: if (true) return; works (with warning "Dead code" which I don't care and can suppress)!
if I simply use return; only then I get the "unreachable code" error.

Note: A simple "This can't be done without using if" is also an acceptable answer, provided a reference.

like image 458
kobik Avatar asked Dec 25 '22 14:12

kobik


2 Answers

No, Java does not support an unconditional return in the middle of a code block, since it doesn't "make sense" in the general scheme of things. (There are good reasons that the Java compiler does and must do fairly strong control flow analysis, and if the compiler allowed it the JVM verifier would still reject it.)

like image 106
Hot Licks Avatar answered Jan 05 '23 00:01

Hot Licks


The problem is that there is:

if (true) return;

which will always call return, therefore the latter code is unreachable. If you use a real condition there's not going to be this warning.

But if you just want to test part of the method I would suggest just commenting the rest of the method that will be tested later.

like image 36
Kuba Spatny Avatar answered Jan 05 '23 00:01

Kuba Spatny