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

前端 未结 5 2028
遇见更好的自我
遇见更好的自我 2020-12-14 05:08

Consider a function of the following general form:

Foo findFoo(Collection foos, otherarguments)
throws ObjectNotFoundException {
    for(Foo foo :         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 06:03

    With Java 8, I would recommend using an Optional for this use case.

    Optional findUserByName(Collection users, String name){
        Optional value = users
            .stream()
            .filter(a -> a.equals(name))
            .findFirst();
    }
    

    This also makes it very clear to the caller that the optional can be empty if the value is not found. If you really want to throw an exception, you can use orElseThrows in Optional to achieve it.

提交回复
热议问题