Best practice: throwing Exception or using Validat

2019-07-31 17:01发布

问题:

Recently I've been into multiple arguments on whether to throw an exception on false User Input.

Example: I'm trying to login though my account is not activated. As the programmer in an OO-language, I could handle this in a few ways. For this case, lets stick to these two:

  1. Throw a custom Exception from the local Service with a representative way, extending Exception. Catching this in the class handling User Input.
  2. Use a Validator to call the local Service to check whether this account is logged in.

My vision, like many others, an Exception represents a fault in the program. E.g. database unreachable, error in parsing data.

Vision of many others as well, the case of logging in without being activated is not a succesful scenario on any use case and will thus fail. This shouldn't not happen and is worth throwing an Exception for.

Personally, I would handle this kind of problem with a Validator, sticking to Exceptions for just the faults in the program. However though, I would like to get a constructive answer on which case is preferred. If possible, referring to any documentation. I'm using Java, though this problem is not restricted to any language (as long as it's OO I guess).

回答1:

In case of a validation error, the flow of your application must be interrupted. For example, you must terminate a singing up progress if an invalid mail address supplied. Thus, the exceptions can be used for the purpose of user input validation.

As an example use, you can check JSF. It benefits from exception mechanism of Java to handle user input validations. The following links can be useful:

  • http://www.mkyong.com/jsf2/custom-validator-in-jsf-2-0/
  • http://www.ibm.com/developerworks/library/j-jsf3/