2

I am a bit confused.

What MSDN says for ArgumentException is:

"The exception that is thrown when one of the arguments provided to a method is not valid."

So I would throw an exception if the passed arguments to my method are not valid.

But also I found out that it is suggested to return boolean plus a string for reason. -instead of throwing an exception.

So,

Question : When validationg method parameters, and when the parameters are not valid, when should the Validation method throw an exception and when it should not?

pencilCake
  • 51,323
  • 85
  • 226
  • 363

1 Answers1

9

If you have a method whose purpose it is to validate its arguments (for example: is this a valid username/password combination), by all means return a bool (false = invalid) plus a reason. Do not throw an exception for an expected situation (if it's not expected, why validate?)

The situation is different if you have a "Process" method: there you must have valid parameters, so it is reasonable to throw an exception (stating the problem) when they are invalid.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
  • +1 Agree. However, if you need to return a bool with a string IMO you should return a class that encapsulates the bool and string together. Don't use output params, they just lead to a headache when someone comes to maintain/refactor your code. – bytedev Jun 07 '13 at 14:42
  • @nashwan: An advantage of having a class to encapsulate the failure cause is that it may be possible to have derived classes include more information applicable to certain types of failures. – supercat Aug 05 '13 at 16:35