参见英文答案 > Why is “throw null” not creating a compilation error in Java? 4个
运行时:
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)
除了一个非常愚蠢的面试问题(请不要在面试中问这个)我看不出任何理由抛出null.也许你想被解雇,但那是……我的意思是,为什么其他人会抛出空?
有趣的事实IntelliJ IDEA 12告诉我,我的行,e instanceof NullPointerException,将永远是假的.这根本不是真的.
解决方法:
看起来并不是将null视为NullPointerException,而是尝试抛出null本身的行为会抛出NullPointerException.
换句话说,抛出检查其参数是非空的,如果它是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’.