Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use custom exception [duplicate]

Tags:

c#

exception

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?

like image 956
GurdeepS Avatar asked Sep 16 '25 22:09

GurdeepS


2 Answers

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.

like image 131
MK. Avatar answered Sep 19 '25 14:09

MK.


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.

like image 34
Anthony Pegram Avatar answered Sep 19 '25 12:09

Anthony Pegram