1

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).

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Menno
  • 12,175
  • 14
  • 56
  • 88
  • 2
    Bad user input is *not* an exceptional case, so no you should not use exceptions for this. – PeeHaa May 01 '13 at 09:16
  • That's my vision as well, though I'm not sure whether this is widely known as good practice. Hence this question. – Menno May 01 '13 at 09:17
  • Check this post: http://stackoverflow.com/questions/77127/when-to-throw-an-exception. Generally, use exceptions when a method cannot deal with a situation and thinks the caller will be better quipped to do so. – iluxa May 01 '13 at 09:21
  • @iluxa: So, in my given case you'd throw an `Exception` from the `Service` since the frontend class won't have the database available? Catching the exception in this frontend class ofcourse. – Menno May 01 '13 at 09:29
  • 2
    nope, i'd expect `validateUserInput()` to return a `ValidationResult` instead of throwing. – iluxa May 01 '13 at 09:33

1 Answers1

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:

ovunccetin
  • 8,443
  • 5
  • 42
  • 53