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 可以吗?


- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01