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

后端 未结 8 995
悲哀的现实
悲哀的现实 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:27

    My rule of thumb is when the client (the caller) might reasonably want to do something different, depending on the type of exception thrown, the additional exception types are warranted. More often than not, however, the extra exception types are not needed. For instance, if the caller is writing code like

    try {
         doIt();
    } catch (ExceptionType1 ex1) {
         // do something useful
    } catch (ExceptionType2 ex2) {
         // do the exact same useful thing that was done in the block above
    }
    

    then clearly the additional exception types are not needed. All too often I see (or am forced to write) code like this because the code being called was overzealous in its creation of new exception types.

提交回复
热议问题