When to use custom exception [duplicate]
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 re开发者_JS百科al-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.
I use custom exceptions when I plan on treating them differently (or think they should be treated differently). For many situations, the general exceptions with a good message are good enough.
If all you plan on doing in the catch is display the message, then you don't get much out of custom exceptions.
Most of the time, I would recommend an exception that already exists. Like @Anthony says with the ArgumentException
. You can always leave a message inside the Exception if you want.
Sometimes, it is handy to have your custom exceptions. For example when you have such code:
catch(ArgumentException e)
{
if(e.Message.Equals("The argument was bigger than 0"))
// do something
else
// do something else
}
That would result in messy code and maybe a custom event or wrapper exception would be more appropriate.
Maybe you could check this blog as well: http://blogs.msdn.com/b/jaredpar/archive/2008/10/20/custom-exceptions-when-should-you-create-them.aspx
It sounds like you are attempting to create exceptions that duplicate the functionality of existing exceptions. For example, your empty basket scenario could be handled by throw new ArgumentException("Basket not instantiated");
When in doubt, fall back to the Exception Design Guidelines on MSDN.
精彩评论