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

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

    It depends on your method's documented interface contract:

    If your method's documentation states that the name argument must correspond to the name of an existing user, then it's appropriate to throw IllegalArgumentException if the name isn't found, because it means the caller violated the method's requirements by passing a name that doesn't correspond to a user.

    If your method doesn't say that the name must correspond to an existing user, then passing an unknown name is not an error and you shouldn't throw an exception at all. Returning null would be appropriate in this situation.

    Note that your findUserByName method is basically reinventing the Map.get method, which returns null if the specified key isn't found.

提交回复
热议问题