Question

I have a simple recursive factorial program. The main point of this exercise is to handle exceptions. We've been imposed with the limitations of having no negative numbers and no number larger than 12.

{
    int factorial(int);
    int number = 0;
    string s;
    while(number != -1)
    {
        cout << "Please enter a number 1 - 12 " <<endl;
        cout << "or -1 to quit the program: ";
        try{
        cin >> number;
        if (number < 0 || number > 12)
            throw number;
        else
            cout << number << " factorial is: " << factorial(number)<<"\n" << endl;
        }catch(int number)
        {
        cout<< "Your number violates the rules; " <<number<<" is either negative or greater than 12.\n"<<endl;
    }
    }

}

int factorial(int number) {
    int temp;
    if(number <=1)
        return 1;
    temp = number * factorial(number - 1);
    return temp;
}

My error handling seems like it's working fine, and it's a new concept to me. However, I'd like to do a better job of handling errors. For example, when I type in anything that's not a number, like say a "p" the program starts an infinite loop. How could I code to check and make sure that it's indeed a number a user is putting in?

Thank you.

Was it helpful?

Solution

Add another condition to test the input. For example you can do this.

...
try{
        cin >> number;
        if (!cin) {
        //error msg here
        break; 
     }  else if (number < 0 || number > 12)
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top