Can I check if a void method returned?

Frozn picture Frozn · Nov 3, 2014 · Viewed 7.3k times · Source

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?

Answer

Theodoros Chatzigiannakis picture Theodoros Chatzigiannakis · Nov 3, 2014

You are right that the practices you described are considered bad in Java (and other modern languages).

The most common acceptable practices for your scenario are:

  • Make the method throw an exception. Do this if the "failing" code path shouldn't happen under normal circumstances.
  • Make the method's return type bool to indicate success or failure. Do this if the "failing" code path can happen under normal circumstances as well.