Why does throwing an unchecked exception removes the "missing return statement" error

207 views Asked by At

I am very new at programming and the problem thus might seem very silly. The below mentioned method has a return type as an int array. When we don't throw any unchecked exception it throws an error which I understand. But why does including an unchecked exception removes that error? It still does not have any return statement, isn't it correct?

public static int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == target - nums[i]) {
                    return new int[] { i, j };
                }
            }
        }
        //throw new IllegalArgumentException("No two sum solution");
    }
3

There are 3 answers

3
fose On BEST ANSWER

There are cases where your program never reaches the inner return statement. E.g. if nums has a length of 0 or if nums[j] == target - nums[i] is never true. For these cases the method needs either return something or it can throw an exception. It is your decision what is the correct behaviour for your use case. If nothing is defined for such cases and your IDE would let you get through with it you would have broken code. If you throw an exception instead of doing nothing your IDE says its fine because your code is correct on a technical level.

0
LowKeyEnergy On

The exception forcibly punts you from the called method. The calling method is then forced to catch the exception and continue computation without access to the return value of the called method.

If the exception is unavoidable / unconditional, then a return statement that follows is never necessary or useful.

1
Andy Turner On

There is no actual requirement for there to be a return statement in a method with a non-void return type. For example:

int huh() {
  while (true) {}
}

is legal.

The requirement is that the method can't complete normally (JLS):

If a method is declared to have a return type (§8.4.5), then a compile-time error occurs if the body of the method can complete normally (§14.1).

Normal completion is basically when execution "falls off the bottom" of the method, that is, reaches the end of the method without encountering a return or throw statement.

So, if you put a throw statement at the end of your method, execution can't reach the end of the method, so it's legal.

In the case of the huh() example above, the while loop doesn't complete normally, so execution cannot reach the end of the method, so you don't need a return or throw there.