当检索方法无法产生返回值时,它应该返回“null"还是抛出异常? [英] Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

查看:21
本文介绍了当检索方法无法产生返回值时,它应该返回“null"还是抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 java 语言,我有一个方法,如果找到它,它应该返回一个对象.

I am using java language,I have a method that is supposed to return an object if it is found.

如果没有找到,我应该:

If it is not found, should I:

  1. 返回空
  2. 抛出异常
  3. 其他

哪个是最佳实践或惯用语?

Which is the best practise or idiom?

推荐答案

作为一般规则,如果该方法应始终返回一个对象,则处理异常.如果您预计偶尔会出现空值并希望以某种方式处理它,请使用空值.

As a general rule, if the method should always return an object, then go with the exception. If you anticipate the occasional null and want to handle it in a certain way, go with the null.

无论你做什么,我都强烈建议不要使用第三个选项:返回一个显示WTF"的字符串.

Whatever you do, I highly advise against the third option: Returning a string that says "WTF".

这篇关于当检索方法无法产生返回值时,它应该返回“null"还是抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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