抛出null时为什么没有编译错误?

时间:2019-04-05 12:13:14

标签: java exception

我看到一个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
    }
}

0 个答案:

没有答案
相关问题