当运行这个时:
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?
(实际上,我不知道如果我抛出null是否是“upcast”,因为我正在抛出null)
除了作为一个非常愚蠢的面试问题(请不要在面试中问这个问题),我看不到任何理由去throw null
。也许你想被解雇,但那...我是说,为什么其他人会throw null
呢?
有趣的事实IntelliJ IDEA 12告诉我,我的代码e instanceof NullPointerException
将永远返回false,这完全不是真的。
e
是null
,则无论XYZ
是什么,e instanceof XYZ
都将返回false
。换句话说,你没有捕获到null
,而是捕获了一个实际的NullPointerException
实例。至于“为什么会有人throw null
”,可能是不经意地这样做(例如throw this.lastException();
,其中lastException()
返回null
)。至于“有趣的事实” - 我想IntelliJ并不那么智能。请提交一个错误报告! - Ted Hoppe instanceof NullPointerException
将永远为false,并不正确。” - 这句话是否有双关语的意味? - BlueRaja - Danny Pflughoeftthrow
语句可以抛出引用类型的“对象”..由于对象可以为null,它允许您抛出null值。 - Anirudhanull
有些特殊,因为它不受类型检查的限制。否则,如果你刚好没有河马,你就不能从返回Hippopotamus
的方法中返回null
。 - Hot Licks