Use exceptions for input validation...

R

redefined.horizons

I'm new to C#, (coming from a Java programming background), and I have
a question about the correct use of exceptions. My book "Programming
C#" by O'Reilly says the following in Chapter 11, "Handling
Exceptions", on page 245:

"An error is caused by user action. For example, the user might enter a
number where a letter is expected. Once again, an error might cause an
exception, but you can still prevent that by catching errors with
validation code. Whenever possible, errors should be anticipated and
prevented."

I have a situation where I want to set an integer property of a C#
class to a value between 1 and 9. I was going to throw exceptions if
the user passed in an int value to the setter of the property that was
less than one or more than 9. Now I am not sure this is the correct
thing to do. I could just pass a message out to the console explaining
the invalid input, but if the setter was called by another object, and
not as the result of a direct user action I think an exception with a
stack trace would be more appropriate.

However, I won't know when the setter for the property is being acessed
via direct interaction with the user, or programattically by another
object.

What is the best practice for C# development in this situation. Do I
throw an exception, or do I write some validation code? What would I
put in the validation code in this particular situation?

Thanks,

Scott Huey
 
I

Ian Suttle

Hi Scott,

Since this code can be accessed from multiple calling sources it would
be best to maintain a consistent experience. This would be best
accomplished by raising a custom exception and depend on the calling
applications to handle that exception. The calling applications should
also do their own validation to ensure the value is correct and handle
wrong values as appropriate.

I hope this answers your question.

Ian Suttle
http://www.iansuttle.com
 
R

redefined.horizons

Ian and Greg,

Thank you both for the quick responses. Your answers were just what I
was looking for.

Scott Huey
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top