以编程方式抛出 NullPointerException 是否可以? [英] Is it okay to throw NullPointerException programmatically?
问题描述
当有后置条件时,方法的返回值不能为空,怎么办?
When there is a post-condition, that return value of a method must not be null, what can be done?
我能做到
assert returnValue != null : "Not acceptable null value";
但是断言可以关闭!
这样可以吗
if(returnValue==null)
{
throw new NullPointerException("return value is null at method AAA");
}
?
或者对于这种情况使用用户定义的异常(如 NullReturnValueException )更好吗?
Or is it better to use a user-defined exception (like NullReturnValueException ) for such a condition?
推荐答案
我认为在 JVM 为您执行之前尽早抛出 NPE 没有问题 - 特别是对于空参数.似乎对此存在一些争论,但 Java SE 库中有许多示例正是这样做的.我不明白为什么NPE在你自己不能扔的方面应该是神圣的.
I see no problem with throwing a NPE as early as possible before the JVM does it for you - in particular for null arguments. There seems to be some debate about this, but there are many examples in the Java SE libraries that does exactly this. I cannot see why NPE should be holy in the aspect that you are not able to throw it yourself.
不过,我离题了.这个问题是关于不同的东西.您正在谈论一个后置条件,说明返回值不能为空.在这种情况下,null 肯定意味着您在方法内部有一个错误?
However, I digress. This question is about something different. You are talking about a post-condition stating that the return value mustn't be null. Surely null in this case would mean you have a bug inside the very method?
你会如何记录这个?如果返回值意外为空,此方法会抛出 NullPointerException"?没有解释这怎么会发生?不,我会在这里使用断言.异常应该用于可能发生的错误 - 不要涵盖如果方法内部有问题可能发生的事情,因为这对任何人都没有帮助.
How would you even document this? "This method throws a NullPointerException if the return value unexpectedly is null"? Without explaining how this could happen? No, I would use an assertion here. Exceptions should be used for errors that can conceivably happen - not to cover things that can happen if there's something wrong inside the method, because that does not help anybody.
这篇关于以编程方式抛出 NullPointerException 是否可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!