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

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

返回null 抛出异常 其他

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


当前回答

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

其他回答

如果您总是希望找到一个值,那么如果缺少该值则抛出异常。这个例外意味着有问题。

如果该值可以缺失或存在,并且两者都对应用程序逻辑有效,则返回null。

更重要的是:在代码的其他地方做什么?一致性很重要。

或者返回一个Option

选项基本上是一个容器类,它强制客户端处理展位案例。Scala有这个概念,查查它的API。

然后你在这个对象上有T getOrElse(T valueIfNull)这样的方法,它们要么返回找到的对象,要么返回客户端指定的替代对象。

如果方法返回一个集合,则返回一个空集合(如上所述)。但请不要收钱。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或其他语言中)!所以不要返回在编译时没有检查的空值。

它不包含对象可能发生在正常操作期间,应该由调用者返回NULL来处理。

如果不包含对象表明调用代码或内部状态存在错误,则执行断言。

如果不包含该对象,则表示不经常发生事件。(就像有人从商店中删除了一件商品,而你同时还在结账。)然后抛出异常。

如果您正在使用抛出异常的库或其他类,则应该重新抛出异常。这里有一个例子。Example2.java类似于library,而Example.java使用它的对象。Main.java就是一个处理这个异常的例子。您应该向调用端的用户显示有意义的消息和堆栈跟踪(如果需要)。

Main.java

public class Main {
public static void main(String[] args) {
    Example example = new Example();

    try {
        Example2 obj = example.doExample();

        if(obj == null){
            System.out.println("Hey object is null!");
        }
    } catch (Exception e) {
        System.out.println("Congratulations, you caught the exception!");
        System.out.println("Here is stack trace:");
        e.printStackTrace();
    }
}
}

Example.java

/**
 * Example.java
 * @author Seval
 * @date 10/22/2014
 */
public class Example {
    /**
     * Returns Example2 object
     * If there is no Example2 object, throws exception
     * 
     * @return obj Example2
     * @throws Exception
     */
    public Example2 doExample() throws Exception {
        try {
            // Get the object
            Example2 obj = new Example2();

            return obj;

        } catch (Exception e) {
            // Log the exception and rethrow
            // Log.logException(e);
            throw e;
        }

    }
}

Example2.java

 /**
 * Example2.java
 * @author Seval
 *
 */
public class Example2 {
    /**
     * Constructor of Example2
     * @throws Exception
     */
    public Example2() throws Exception{
        throw new Exception("Please set the \"obj\"");
    }

}