views:

45

answers:

2

Is it a good practise to use custom business exceptions (e.g. BusinessRuleViolationException) to control the flow of user-errors/user-incorrect-inputs???

The classic approach: I have a web service, where I have 2 methods, one is the 'checker' (UsernameAlreadyExists()) and the other one is 'creator' (CreateUsername())... So if I want to create a username, I have to do 2 roundtrips to webservice, 1.check, 2.if check is OK, create.

What about using UsernameAlreadyExistsException? So I call only the 2. web service method (CrateUsername()), which contains the check and if not successfull, it throws the UsernameAlreadyExistsException. So the end goal is to have only one round trip to web service and the checking can be contained also in other web service methods (so I avoid calling the UsernameAlreadyExists() all the times..). Furthermore I can use this kind of business error handling with other web service calls completely avoiding the checking prior the call.

+2  A: 

Using exceptions to manage application flow is a bad idea. If you think that you can check something, rather take the output to decide. Rather than a called method throwing an exception and the caller decide on what to do on the exception, it is better to let the called method return a state and let the caller decide the flow on the value of the state.

Kangkan
1. it is not the application-control-flow but user-error (not internal errors/exceptions)2. I forgot to add that these business exceptions are handled in a nice way by the client/consument (exception wrapped as an error object with nice, user-friendly description
If you are using exceptions just to inform the user about the exception in the system (not due to system's internal error) then using a custom exception is a general practice. So in that case you may go forward with a custom exception class.
Kangkan
Exceptions were not ment to be used for controlling the flow, they are for special cases. If the fact that you get UserAlreadyExistsException means your system is corrupted or business use case went wrong, than it is ok, but to simply check if user can be created it is very wrong imho.
Gabriel Ščerbák
I found some resources which might sched a bit of light into your understanding of exceptions:http://www.se-radio.net/podcast/2006-02/episode-7-error-handlinghttp://www.se-radio.net/podcast/2006-07/episode-21-error-handling-pt-2
Gabriel Ščerbák
+2  A: 

Some people do, and they are really good at developing. Sometimes it is just easier and faster for the developer to throw an exception instead o chaining back a return value.

It must be taken into account that throwing an exception is no cheap, though. Stack TRace and the like is big, and in heavy use can impact performance.

I think it is OK to use exceptions sometimes when it is just really necessary, but it should not be your main way of controlling the flow. just my 2/100

Daniel Dolz