以编程方式抛出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,特别是对于null参数。似乎有一些关于这个的争论,但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。在这种情况下肯定为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?
你甚至会如何记录这个? 如果返回值意外为null,则此方法将抛出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屋!