javaexceptionstandard-library

Is there a standard java exception class that means "The object was not found"?


Consider a function of the following general form:

Foo findFoo(Collection<Foo> foos, otherarguments)
throws ObjectNotFoundException {
    for(Foo foo : foos){
        if(/* foo meets some condition*/){
            return foo;
        }
    }
    throw new ObjectNotFoundException();
}

A concrete case, for example, would be:

User findUserByName(Collection<User> users, String name)
throws ObjectNotFoundException {
    for(User user : users){
        if(user.getName().equals(name)){
            return user;
        }
    }
    throw new ObjectNotFoundException();
}

These functions throw an exception if the object is not found. I can create a custom exception class for this purpose (in the examples, ObjectNotFoundException) but I would prefer to use an existing class. However, I could not find any exception class with this meaning in the standard java library. Do you know if there is a standard exception that can be used here?


Solution

  • Do you know if there is a standard exception that can be used here?

    There are a couple of exceptions that could be used (e.g. NoSuchElementException or IllegalArgumentException) but the answer really depends on the semantics that you intend to convey:

    (But don't be tempted to use UnknownUserException. That would be horribly wrong; read the javadoc!)


    It is also worth considering returning null, especially if lookup failure is likely to be a fairly common (non-exceptional) event in your application. However, the downside of returning null is that the caller needs to check for null or risk unexpected NullPointerExceptions. Indeed, I would argue that over-use of null is worse than over-use of exceptions. The former can result in unreliable applications, whereas the latter is "only" bad for performance1.

    For Java 8 and onwards, returning an Optional would be a cleaner choice than returning a null.

    1 - The performance impact of throwing and catching an exception can depend on the Java version. Starting in (I think) Java 8, the C2 JIT compiler can optimize away the capture of an exception's stacktrace under some circumstances; e.g. When does JVM start to omit stack traces?.


    In these things, it is important to look beyond the dogmas, and make up your mind based on what the actual context requires.