为什么抛出未经检查的异常会消除 "missing return statement" 错误

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

我是编程新手,因此这个问题可能看起来很愚蠢。下面提到的方法有一个 return 类型作为一个 int 数组。当我们不抛出任何未经检查的异常时,它会抛出一个我理解的错误。但是为什么包含未经检查的异常会消除该错误呢?它仍然没有任何 return 声明,对吗?

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

在某些情况下,您的程序永远不会到达内部 return 语句。例如。如果 nums 的长度为 0 或者如果 nums[j] == target - nums[i] 永远不会为真。对于这些情况,该方法要么需要 return 东西,要么会抛出异常。您可以决定您的用例的正确行为是什么。如果没有为这种情况定义任何内容,并且您的 IDE 会让您通过它,那么您就会破坏代码。如果您抛出异常而不是什么都不做,您的 IDE 表示没问题,因为您的代码在技术层面上是正确的。

异常强行将您从被调用的方法中踢出。然后强制调用方法捕获异常并继续计算,而无需访问被调用方法的 return 值。

如果异常是不可避免的/无条件的,那么后面的 return 语句就没有必要或有用。

在具有非 void return 类型的方法中没有实际要求 return 语句。例如:

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

legal

要求是方法无法正常完成(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).

正常完成基本上是方法执行“掉底”,即到达方法末尾而没有遇到return或throw语句。

所以,如果你在你的方法的末尾放一个throw语句,执行到方法的末尾是不可能的,所以是合法的。

在上面的 huh() 示例中,while 循环没有正常完成,因此执行无法到达方法的末尾,因此您不需要 return 或扔到那里。