What is the general rule of thumbs for creating an Exception in Java?

后端 未结 8 997
悲哀的现实
悲哀的现实 2021-01-07 19:04

I have been in both situations:

  • Creating too many custom Exceptions
  • Using too many general Exception class

In both cases the project s

相关标签:
8条回答
  • 2021-01-07 19:35

    My own rule of thumb:

    I never throw Exception, except in unit tests when what you throw is irrelevant and theres no reason to spend any extra time on it.

    I create my own custom exception type for errors occuring in my custom business logic. This exception type is used as much as possible for recasting other exceptions, except in cases where it makes sense for the client to have visibility into what actually occurred.

    0 讨论(0)
  • 2021-01-07 19:40

    Don't eat exceptions, throw them https://stackoverflow.com/a/921583/1097600

    Avoid creating your own exception. Use the below ones that are already there.

    IllegalStateException
    UnsupportedOperationException
    IllegalArgumentException
    NoSuchElementException
    NullPointerException
    

    Throw unchecked exceptions.

    Example

    public void validate(MyObject myObjectInstance) {
        if (!myObjectList.contains(myObjectInstance))
            throw new NoSuchElementException("object not present in list");
    }
    
    0 讨论(0)
提交回复
热议问题