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

后端 未结 8 1168
悲哀的现实
悲哀的现实 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: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");
    }
    

提交回复
热议问题