When/why to use custom exceptions
I read a thread on this topic on this very forum which listed some reasons to use custom exceptions but none of them really seemed strong reasons (can't remember the reasons now).
So why would you use cus开发者_如何学Pythontom exceptins? In particular, I have never understood the decision making process between using a standard or custom exception to indicate a shopping basket is null (I think a custom one is used as an empty collection is not exceptional and this is a business process thing). More clarification is needed, however.
Thanks
Here is my take:
- If any of the standard exceptions do not match the exceptional situation, create a custom exception
- If there is additional information that you need to pass in to the exception, create a custom exception
- If there is meaning to having your own exception class, create a custom exception (that is, other developers will benefit from being able to catch it)
In regards to things like null arguments - I would never use a custom exception. The NullArgumentException (.NET) / IllegalArgumentException (Java) is perfectly satisfactory.
Jared Par has a blog entry about this, here.
精彩评论