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

如果没有找到,我是否应该:

返回null 抛出异常 其他

哪一个是最好的实践或习语?


当前回答

如果null从不表示错误,则返回null。

如果null始终是错误,则抛出异常。

如果null有时是一个异常,那么编写两个例程。一个例程抛出异常,另一个是布尔测试例程,它在输出参数中返回对象,如果没有找到对象,则返回false。

很难滥用Try例程。很容易忘记检查null。

所以当null是一个错误时,你只需要写

object o = FindObject();

当null不是错误时,您可以编写如下代码

if (TryFindObject(out object o)
  // Do something with o
else
  // o was not found

其他回答

我更喜欢只返回null,并依赖于调用者来适当地处理它。(因为没有更好的词)例外是,如果我绝对“确定”这个方法将返回一个对象。在这种情况下,失败是一个例外,应该和应该抛出。

与您正在使用的API保持一致。

返回null,异常就是:你的代码所做的不是预期的事情。

抛出异常的好处:

Cleaner control flow in your calling code. Checking for null injects a conditional branch which is natively handled by try/catch. Checking for null doesn't indicate what it is you're checking for - are you checking for null because you're looking for an error you're expecting, or are you checking for null so you don't pass it further on downchain? Removes ambiguity of what "null" means. Is null representative of an error or is null what is actually stored in the value? Hard to say when you only have one thing to base that determination off of. Improved consistency between method behavior in an application. Exceptions are typically exposed in method signatures, so you're more able to understand what edge cases the methods in an application account for, and what information your application can react to in a predictable manner.

有关更多示例的解释,请参见:http://metatations.com/2011/11/17/returning-null-vs-throwing-an-exception/

不要认为任何人都提到了异常处理中的开销——需要额外的资源来加载和处理异常,所以除非它是一个真正的应用程序杀死或进程停止事件(继续下去会造成更多的伤害而不是好处),否则我会选择返回一个调用环境可以解释为它认为合适的值。