我使用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\"");
    }

}

其他回答

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

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

否则,返回null。

如果没有找到它是一个异常事件(即在正常情况下它应该在那里),那么就扔掉它。否则,返回一个“notfound”值(可以为空,但不一定),或者甚至让方法返回一个布尔值来表示found/notfound,并为实际对象返回一个out参数。

我只是想概括一下之前提到的选项,并添加一些新的选项:

返回null 抛出异常 使用空对象模式 为您的方法提供一个布尔参数,以便调用者可以选择是否希望您抛出异常 提供一个额外的参数,以便调用者可以设置一个值,如果没有找到值,则返回该值

或者你可以把这些选项结合起来:

提供getter的多个重载版本,以便调用者可以决定采用哪种方式。在大多数情况下,只有第一个有搜索算法的实现,其他的只是围绕着第一个:

Object findObjectOrNull(String key);
Object findObjectOrThrow(String key) throws SomeException;
Object findObjectOrCreate(String key, SomeClass dataNeededToCreateNewObject);
Object findObjectOrDefault(String key, Object defaultReturnValue);

即使您选择只提供一个实现,您也可能希望使用这样的命名约定来阐明您的契约,并且它有助于您决定添加其他实现。

你不应该过度使用它,但它可能是有帮助的,特别是当你编写一个helper类时,你将在数百个不同的应用程序中使用许多不同的错误处理约定。

在一些函数中,我添加了一个参数:

..., bool verify = true)

True表示抛出,false表示返回错误返回值。这样,任何使用这个函数的人都有两个选项。为了方便那些忘记错误处理的人,默认值应该是true。

抛出异常的好处:

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/