Is it okay to throw NullPointerException programmatically?(以编程方式抛出 NullPointerException 可以吗?)
问题描述
当有后置条件时,方法的返回值不能为null,怎么办?
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 之前尽早抛出 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 意味着您有一个错误方法内部?
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 可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:以编程方式抛出 NullPointerException 可以吗?


基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01