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

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

    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:

    • NoSuchElementException tends to be used when you are stepping through an sequence or enumeration, where what you have here is a lookup.

    • IllegalArgumentException tends to imply that the argument is in error, but in this case, it could be that the assumptions of the caller are incorrect, or something that is specific to the application logic.

    • A custom exception allows you to say (in the javadocs) exactly what the exception means. You can also declare it to be checked ... if that it appropriate.

    (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 performance.

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


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

提交回复
热议问题