According to the .NET Framework General Reference: Error Raising and Handling Guidelines exceptions should not be thrown during 'normal' operations. Is invalid user input to a web form, say the user enters a duplicate name, considered normal? !! IMPORTANT !!: I'm sure we pretty much all have an opinion on this, please include a reference to a reliable source.
EDIT:
A little more background: I'm questioning the approch to model validation advocated by a book I'm reading. The book is suggesting that you throw a custom exception from a repository when provided with invalid data to save. Now, this seems to me to violate MS guidlines because you are using exceptions as flow control...unless recieving invalid data is consider outside of 'normal' operation. I just want to see if there is any further guidance from a reliable source to resolve this.
ANOTHER EDIT:
OK so two and a half years later, I'm moving this repository to a WCF service and using exceptions in this method turned out to be a bad idea. Oh well.
Generally no, but I can think of one exception to the rule that I have personally encountered.
We require that our domain objects are valid at all times. If an attempt is made to create or pass bad data, we do thrown an exception from the domain object. In this case, though, it is an "exceptional circumstance". Why? The logic is that bad data should never make it into the domain. Somewhere along that call stack is a place where invalid data was able to be entered into the system - whether it was through a miscalculation, bad data from the underlying data source, or from user input.
Another, ancillary reason we do this, is that the domain objects and their rules are encapsulated within a physically separated assembly. By doing this, we make sure that we provide as much information to the caller, as possible. Because of the implications of what is happening, the assumption is made that the caller will log this so that there is visibility into what truly is an issue - that of not validating the data.
So, in the case where you are looking to see if the data has not been validated or that the rules to validate themselves are at odds with your data persistence methods/functionality, I think that it is perfectly valid to throw. In all other cases, I tend to avoid throwing for invalid input.
Generally speaking, invalid or ill-formed input is not consider 'exceptional' and should be handled using something other than exceptions. But note that this is a guideline - there may well be situations where using exceptions to handle the problem would result in better code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With