javaexceptionreturnthrowunchecked-exception

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


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");
    }

Solution

  • 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.