以编程方式抛出 NullPointerException 可以吗? [英] Is it okay to throw NullPointerException programmatically?

查看:47
本文介绍了以编程方式抛出 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 可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆