Possible Duplicate:
Create custom exception or use built-in exceptions?
Hi,
In program design, is it normal to model exceptions for business constraints? E.g. if xyz must be >1 in order to get abc (a basket object must exist before being able to add objects), and the basket does not exist, is this a good enough reason to have a custom exception to model this real-world scenario?
What reasons contribute to using custom exceptions?
I think the question is not whether one should create a custom exception class, but whether one should use exception for normal conditions of incorrect input, i.e. if you ask a user to create a new password, should the code internally throw PasswordTooWeakException (or InvalidArgumentException) when the password is too weak, or should handle it in another way. If that is the question, my answer is no, you should not use exceptions in this case. Exceptions are for exceptional cases only, i.e. error situations, where something not expected happens.
If the basket does not exist, sounds like a ArgumentNullException
or an InvalidOperationException
depending whether the variable is a parameter or not. If xyz must be greater than 1, sounds like an ArgumentException
. The latter case also sounds like something you could handle without resorting to exceptions depending upon where the validation is taking place.
There are many of already defined exceptions as part of the standard library. My advice is to rely upon those until you can clearly demonstrate that such exceptions truly do not cover your particular scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With