I just want to ask, if it is possible to check if a void method "cancelled" itself by calling return;
?
For example in my main I call calculate(myArray);
, which is defined as follows:
public static void calculate(Object[] array) {
if (array == null)
return;
// do stuff
}
Is their a way to know, if it returned or not? My thoughts were making a "global" boolean which is changed to true right before we return and then check its value in main or just change the return type to something like int and when it returned at the beginning we use return -1;
and at the end of the method return 0;
Both is possible but I think neither of them is very good style. Is there an alternative?
No, you cannot. From The Oracle Java tutorials - Returning a Value from a Method:
Any method declared
void
doesn't return a value. It does not need to contain areturn
statement, but it may do so. In such a case, areturn
statement can be used to branch out of a control flow block and exit the method and is simply used like this:return;
There is no way from method invocation to determine if the void
method was completed by a fall-through block or a return;
statement.
Most other methods includes a return type of boolean
and returns false
when something went wrong, or simply throws an IllegalArgumentException
.