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

前端 未结 5 2018
遇见更好的自我
遇见更好的自我 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 05:53

    Exceptions are created to mark exceptional behaviour. In my opinion, object not found situation is not exceptional. I would rewrite your method to return null, if user is not found.

    User findUserByName(Collection users, String name) {
       for(User user : users){
           if(user.getName().equals(name)){
               return user;
          }
        }
      return null; 
    }
    

    This is standard behaviour for many Java Collections. For example, http://docs.oracle.com/javase/7/docs/api/java/util/Map.html#get(java.lang.Object) will return null, when no entry with specified key is in the map.

    You should avoid relying on exceptions in your programms logic.

提交回复
热议问题