首页 > 解决方案 > 为什么抛出null时没有编译错误?

问题描述

我看到一个 Java 代码的参考,其中有一行:

throw null;

我也试过了,没有编译异常,直到现在我以为我们只能抛出异常,我测试了我可以抛出任何数字或对象。为什么我没有得到编译异常?如果我尝试抛出 String 它会给出以下异常,这意味着什么?

No exception of type String can be thrown; an exception type must be a subclass of Throwable

谁能解释一下我可以使用上述代码行的原因和用例吗?

class Solution {
    public int repeatedNTimes(int[] A) {
        for (int i = 0; i < A.length - 1; ++ i) {
            if (A[i] == A[i + 1]) { // any two neighbour numbers 
                return A[i];
            }            
        }
        // could be evenly distributed excluding the above case
        for (int i = 0; i < A.length - 2; ++ i) {
            if (A[i] == A[A.length - 1] || A[i] == A[A.length - 2]) {
                return A[i];
            }
        }
        throw null; // input array is not what has been described
    }
}

标签: javaexception

解决方案


推荐阅读