c# - Is it normal to use many business exceptions if needed? -
is practice define , throw custom exceptions if application needs lots of them?
- entitynotfoundexception
- entityalreadyexistsexception
- entitynotuniqueexception
- entitynotaddedexception
- entitynotupdatedexception
- entitynotdeletedexception
- quizoverexception
- quizexpiredexception
- tablealreadybookedexception
- enddatemustbegreaterthanstartdateexception
i tried name these sample exception names describe purpose could. hope form idea of trying ask.
don't limit imagination these exceptions arise during application's life. consider both crud , business exceptions.
i know throwing , catching exceptions expensive process in terms of performance don't provide more elegant way develop app?
- isn't better throw
entitynotfoundexception
instead of writing if statement check whether entity null? - isn't better throw
entityalreadyexistsexception
instead of writing additional if statement call method check whether entity given id exists? - isn't better throw
entitynotaddedexception
instead of checking return value of type bool specifying whether transaction successful or not? if want return object?
i feel answer "you should not use entitynotfoundexception
instead check if null, should use entityalreadyexistsexception
", "there no holy grail".
i wondering elegant way of doing this?
keeping in mind exceptions supposed represent exceptional circumstances of questions can answered - it depends.
the context of when & intend on throwing particular exception naturally decide whether makes sense. example, if attempt retrieve entity should exist doesn't, throwing entitynotfoundexception
considered appropriate because have exceptional circumstance. on other hand, if checking whether entity exists before creating new 1 argue because know there chance entity may or may not exist it's not exceptional circumstance.
like said, depends on context of situation , nature of application whether should throw exception or not, however, 1 thing don't want end doing controlling program flow exceptions.
to make distinction between when it's suitable use exception vs business logic, ask "is particular situation valid?" or in other words "is ok application find in state?". if answer yes, use logic control flow of application , deal situation, otherwise want throw exception
interrupt program flow , inform user isn't quite right.
Comments
Post a Comment