运行时:
public class WhatTheShoot {
public static void main(String args[]){
try {
throw null;
} catch (Exception e){
System.out.println(e instanceof NullPointerException);
System.out.println(e instanceof FileNotFoundException);
}
}
}
响应是:
true
false
这对我来说相当令人惊叹。我本以为这会导致编译时错误。
为什么我可以在 Java 中抛出 null,并且为什么它会将其向上转换为 NullPointerException?
(实际上,我不知道它是否是“upcast”,因为我抛出的是 null)
除了一个非常非常愚蠢的面试问题(请不要在面试中问这个)我看不出任何理由 throw null
。也许你想被解雇,但那是......我的意思是,为什么还有人 throw null
?
有趣的事实 IntelliJ IDEA 12 告诉我我的行 e instanceof NullPointerException
,永远是假的。这根本不是真的。
最佳答案
看起来并不是 null
被视为 NullPointerException
,而是尝试抛出 null
的行为本身会抛出 NullPointerException
。
换句话说,throw
检查其参数是否为非 null,如果为 null,则抛出 NullPointerException
。
JLS 14.18 specifies这种行为:
If evaluation of the Expression completes normally, producing a null value, then an instance V' of class NullPointerException is created and thrown instead of null. The throw statement then completes abruptly, the reason being a throw with value V'.
关于java - 为什么Java中可以抛出null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55535124/