Help with simple exception handling

I need help understanding why the exception handling is not activating with this code. When I input a letter instead of a number, I get a runtime error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <cctype>

using namespace std;

int main()
{
	int x;
	cout << "Please enter a number" << endl;
	try{
		cin >> x;
		if (isalpha(x)) // or if (!isdigit(x))
		{
			throw 1;
		}
	}
	catch (int x)
	{
		if (x == 1)
		{
			cout << "Enter a digit" << endl;
		}
	}
	cout << x << endl;
	return 0;
}
When you throw the exception, it does not go the catch statement inside main because `throw` statement is short circuiting just like a `return` statement.
So when you throw the int, the code just exits main and whatever called main (the OS in this instance) gets the exception


It's because you are trying to read in an integer, but when you enter a character, `x` is just set to zero which is why you get a 0 at the end.
Last edited on
How would I fix this error? Would I instead throw something such as, char c; ?
Read everything in as a string. Check each character in the string to see if they are non-digit. If you find one that is non-digit, you throw your exception.

If the string only contains digits, convert it to int using std::stoi
I never heard of stoi, I'm glad you brought that up.

So now, I guess I would use a for loop to go through each character in the string and if a character is a non-digit, throw the exception.
The simple solution would be:

1
2
    if ( !(cin >> x) )
        throw 1;


Although it isn't as flexible as reading into a string and checking the contents.
Topic archived. No new replies allowed.