Should I throw an exception on user input errors?
I'm writing a user input library to easily manage the dynamic creation of forms for asking users for data.
I wanted to make the end developer have to 'think' about the bare minimum, so I went with having them throw exceptions instead of returning 'true' or 'false' and remembering to handle the return value etc.
In reality, it's worked out 开发者_如何学JAVAreally well. Throwing exceptions has also given me a side benefit of being able to automatically record user errors in a log, all for 'free' as the creation of the exception causes the logging to be done.
Having said all of that, I was wondering if this is really 'against best practices'? Should I have kept exceptions only for times when I didn't even expect user input error, or is it OK to say "the data from the user has a problem... that's an exception"?
Any thoughts?
Exceptions are for exceptional cases.
Bad user input is an expected case, and (in my opinion) you should always be trying to validate and massage it into the correct format before showing a non-exceptional error message.
symfony's form framework validators throw exceptions.
Personally, I think that's fine, and better as it forces the developer to handle the error from the input, which is obviously important.
I agree with Gareth on this one. Bad user input is an expected condition.
Consider this instead (this is a usual strategy in Java): create an Errors
class. Pass an object of this type to your validators. The validators can leave the object untouched or they can add to it one or more error messages and their associated field. After you pass this through all the validators, inspect the Errors
object to see if it's empty, if not, read it and show the form again together with the errors.
In my personal opinion, it has to do with where you are going to handle the error. If it's sufficiently up the code tree, an Exeption would be wise. If you're just catching it 3 lines below it's a waste of resources (it does contain the complete backtrace), and 'inline' error handling would be fine, for which you can easily add (the same) logging capability.
精彩评论