I have been reading a little about try catch blocks. Could someone show me an example of a try catch that could be used with something like this.
1 2
int choice;
cin >> choice;
Now if you were to input a letter the program either crashes or in my case because I have everything in a bit loop, it goes in to a infinite loop because I check the value of choice later.
So how can the try catch be used to make sure an integer is entered.
Non-integer input is not an exceptional condition, you should check the status of the input stream with an if (or use it as a part of the loop statement):
1 2 3 4 5 6 7
int choice;
cin >> choice;
if(!cin)
{
cout << "What was that?\n";
break;
}
But if you want to know how it could be done with exceptions,
1 2 3 4 5 6 7 8 9 10
cin.exceptions(ios_base::failbit); // throw on rejected input
try {
// some code
int choice;
cin >> choice;
// some more code
} catch(const ios_base::failure& e) {
cout << "What was that?\n";
break;
}
I got Cubbi's answer to work but even though im catching the exception, the program crashes when a letter is entered but with a fancy message now. Also I could not get your first example to work, only with exceptions did i manage to get it to work some what.