Consider a function of the following general form:
Foo findFoo(Collection foos, otherarguments)
throws ObjectNotFoundException {
for(Foo foo :
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.