[英]Why does java allow NPE
How come javac
doesn't emit error on this code? 为什么
javac
不会在此代码上发出错误?
private static int compute(int v) {
return v == 0 ? null : v;
}
Surely, compute(0)
will throw NullPointerException
. 当然,
compute(0)
将抛出NullPointerException
。 I would expect the java compiler to prevent this by doing some basic static code analysis, just like it would prevent 我希望java编译器通过做一些基本的静态代码分析来防止这种情况,就像它会阻止它一样
private static int compute(int v) {
if (v == 0)
return null;
else
return v;
}
Why does java allow NPE?
为什么java允许NPE?
To indicate an exceptional condition (and allow the programmer to potentially recover ). 指示异常情况(并允许程序员可能恢复 )。
In your example, Java allows both autoboxing and unboxing . 在您的示例中,Java允许自动装箱和拆箱 。 The
null
boxes the int
to an Integer
(which is then unboxed to an int
). null
将int
设置为Integer
(然后将其拆箱为int
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.