Reputation: 1713
I was wondering if it's possible to exit a function early, bypassing the remainder of the code in the body. For example:
public class SOMECLASS {
public SOMECLASS( int i ) {
gotoSwitchCase(i);
additionalTask(); // method body is irrelevant
}
private void gotoSwitchCase(int i) {
switch (i) {
case 0:
/* exit ctor prematurely */
break;
default:
/* set some instance variables, return to ctor */
}
}
}
I know that I can insert if(i==0){return;}
at the very beginning of additionalTask()
to skip that part. However, I'm more interested in whether or not there is a way to exit the constructor (or any function) gracefully without visiting the rest of it's body. Similar to an exception, but not as fatal.
Upvotes: 1
Views: 8666
Reputation: 3537
Here's an easy workaround: Return codes. Return 0 to skip the next line.
public class SOMECLASS {
public SOMECLASS(int i) {
if (gotoSwitchCase(i) != 0) {
additionalTask();
}
}
private int gotoSwitchCase(int i) {
switch (i) {
case 0:
return 0;
default:
/* set some instance variables, return to ctor */
return 1;
}
}
}
Also, exceptions aren't fatal if you catch them. You can do Try/Catch in the constructor, and throw from gotoSwitchCase. If you caught the thrown exception in the Constructor, nothing under it will run so you get the same effect.
Of course... you could always just use return
wherever you need to (including constructors)
Upvotes: 3
Reputation: 196
No, you cannot return the execution of the parent function.
But your gotoSwitchCase(...)
function can return -1 if you want to exit prematurely. Then you just have to do a if(gotoSwitchCase(...) == -1) return;
Upvotes: 1
Reputation: 138
If you wish to exit a function early (including the constructor), you can simply use the return;
command. This works in constructors as well.
Edit for clarification: This is the correct way to solve this problem. You can't skip skip the rest of the constructor from the body of gotoSwitchCase
because gotoSwitchCase
could be run from the constructor or any other method from which it is visible.
Upvotes: 9