I've designed a simple program that has a counter class and inside that counter class I have methods that increment the count, deincrement the count, and so on. I then present a menu to the user and have them enter their choice, ex. enter 1 for option one, etc. Well, I don't ever want the count to be negative, so to handle this I had my SubtractCount method of the counter class throw an ArguemetOutOfRangeException when count < 0.
I then had my switch statement catch that exception if it occurred. My question is: Is it bad to use an exception to make sure the count can never be negative? Should I do it differently? Or better yet, is there a better way to accomplish this?
Code snippet:
static void Driver()
{
switch (userChoice)
{
case 1: // if user picks a 1, the count is deincremented
try {
myObjectOfCounterClass.SubtractCount();
}
catch (ArguemetOutOfRangeException ex)
{
console.writeLine(ex.message);
}
break;
// case 2, case 3 etc.
}
class Counter
{
private int count;
public void SubtractCount()
{
if (count < 0)
throw new ArguementOutOfRangeException("The count can never be negative!");
else
count--;
}