Should a retrieval method return #39;null#39; or throw an exception when it can#39;t produce the return value?(检索方法是否应该在无法产生返回值时返回“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:
- 返回空值
- 抛出异常
- 其他
最佳实践或惯用语是什么?
Which is the best practise or idiom?
推荐答案
作为一般规则,如果方法应该总是返回一个对象,那么就排除异常.如果您预计偶尔会出现 null 并希望以某种方式处理它,请使用 null.
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"或抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检索方法是否应该在无法产生返回值时返回“n


基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01