开发者

Should I use custom exceptions to control the flow of application?

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 c开发者_运维知识库an use this kind of business error handling with other web service calls completely avoiding the checking prior the call.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜