java - 为什么抛出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
}
}
解决方案
推荐阅读
- apache-spark - spark cassandra 连接器在回读时丢失数据
- flutter - 使 ListView/SingleChildScrollView 中的列占用屏幕的剩余空间
- r - 在“expss::uselabels()”中使用管道运算符?
- python - 信用卡欺诈的 Python 算法
- javascript - 页面上的多个 VueJS 应用程序共享通用 VueJS 模块
- flutter - 颤动的滚动视图不在流中滚动
- apollo - 我怎样才能捕捉到任何错误(网络和graphql),并防止promise.reject()?
- javascript - 具有多维数组的对象数组
- javascript - 在本机反应中更新 setState 实例
- html - 动画在较小的屏幕中导致滚动条