java.lang.Exception vs. rolling your own exception

后端 未结 10 1201
无人及你
无人及你 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:09

    I would use the exceptions from the Java API when the exception relates to the API. But if an exceptional situation arises that is unique to my own API then I will create an Exception for it. For example if I have a Range object with two properties min and max and the invariant min <= max then I will create an exception InvalidRangeException.

    When I am writing code this helps because I know if the exception originates because I violated one of my own conditions or its something from the Java API.

提交回复
热议问题