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

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

返回null 抛出异常 其他

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


当前回答

作为一般规则,如果方法应该总是返回一个对象,那么就使用例外。如果您预期偶尔会出现null,并希望以某种方式处理它,那么就使用null。

无论你做什么,我强烈建议反对第三种选择:返回一个字符串,说“WTF”。

其他回答

只有在确实是错误时才抛出异常。如果对象不存在是预期行为,则返回null。

否则就是个人喜好的问题了。

这取决于你是否希望找到这个物体。如果你遵循学校的思想,认为exceptions应该用来表示某事,那么,嗯,呃,exceptions已经发生了:

对象发现;返回对象 没有找到对象;抛出异常

否则,返回null。

首选返回null——

如果调用者在不检查的情况下使用它,异常就会在那里发生。

如果调用者并没有真正使用它,不要给他一个try/catch块

这取决于你的方法。如果你的方法应该总是返回一个有效的对象,但却没有找到,那么抛出异常就是正确的方法。如果该方法只是返回一个可能存在也可能不存在的对象(比如联系人的图像),则不应该引发错误。

你可能还想公开一个返回布尔值true/false的方法,如果这个方法实际上会返回一个对象,这样你就不必a)检查null或b)捕捉异常

如果方法返回一个集合,则返回一个空集合(如上所述)。但请不要收钱。EMPTY_LIST或类似的!(以Java为例)

如果该方法检索单个对象,则您有一些选项。

If the method should always find the result and it's a real exception case not to find the object, then you should throw an exception (in Java: please an unchecked Exception) (Java only) If you can tolerate that the method throws a checked exception, throw a project specific ObjectNotFoundException or the like. In this case the compiler says you if you forget to handle the exception. (This is my preferred handling of not found things in Java.) If you say it's really ok, if the object is not found and your Method name is like findBookForAuthorOrReturnNull(..), then you can return null. In this case it is strongly recomminded to use some sort of static check or compiler check, wich prevents dereferencing of the result without a null check. In case of Java it can be eg. FindBugs (see DefaultAnnotation at http://findbugs.sourceforge.net/manual/annotations.html) or IntelliJ-Checking.

如果决定返回null,请小心。如果你不是项目中唯一的程序员,你会在运行时得到nullpointerexception(在Java或其他语言中)!所以不要返回在编译时没有检查的空值。