java.lang.Exception vs. rolling your own exception

后端 未结 10 1204
无人及你
无人及你 2020-12-13 14:30

At what point would you create your own exception class vs. using java.lang.Exception? (All the time? Only if it will be used outside the package? Only if it must contain ad

10条回答
  •  清歌不尽
    2020-12-13 15:08

    Start always by using the common exception classes and then when a need appears to handle it specially, change it.

    1. When creating a method first time, just let exceptions go through.

    2. If there are exceptions that must be handled, those can either be just defined in throws or wrapped to some runtime exception or wrapped own throws exception. I prefer runtime exceptions in many cases. Defining throws definition should be avoided until there is a need for it from API point of view.

    3. Later when a need appears to do specific handling for an exception in some caller, come back and create new exception for it.

    The point is to avoid doing extra work before knowing what is needed.

提交回复
热议问题