This is just a section of the code as the program runs as expected before I started adding exception handling. Still a new subject for me and I reviewed the tutorial here and can't seem to figure out why my catch statement can catch about as well as a no-armed man.
I run the code and input 8, the debugger hangs at the correct throw statement. or full on crashes the program. I tried defining the catch statement to catch an int as well as the throw statement and the program still hangs at the throw statement. I am sure I am missing something simple but I am going bald from scratching my head. Anyone able to help me out?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
cin >> choice1;
do{ //loop until exceptioncheck=true
try{
if (cin.fail()) //exceptioncheck for non int input
{
cin.clear();
cin.ignore();
throw;
}
elseif (choice1>7||choice1<1)
throw;
exceptioncheck=true;
}
catch(...)
{
cout<<"Choice must be a number from 1-7\n";
cout << "Your choice: ";
cin >> choice1;
}Put the code you need help with here.
An exception is an object - like an int or a std::string or a std::runtime_error. The throw keyword causes an exception object to propagate, but we need to say which object we want to throw.
For example, you've got to throw something:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
try
{
throw 24; // throw 24, an int
}
catch(intconst& e) // note: catch exceptions by const reference
{ // this catch block matches ints.
std::cerr << "caught an int\n";
// inside this catch block, there is a current exception object:
// if we cannot handle the exception here, we can cause the current
// exception to be re-thrown
std::cerr << "couldn't handle current exception " << e << '\n';
throw;
} // later on in the program, we might encounter another catch block:
catch (...) // this catch block matches everything
{
std::cerr << "caught something\n";
}
If the statement throw; appears without a current exception, std::terminate() is called.
do{ //loop until exceptioncheck=true
try{
if (cin.fail()) //exception check for non int input
{
cin.clear();
cin.ignore();
throw"Choice must be a number!\n";
}
elseif (choice3>100||choice3<1) // exception check for int range
throw"Choice must be a number from 1-100";
exceptioncheck=true;
}
catch(constchar* msg)
{
cerr << msg << endl;
cout << "Your choice: ";
cin >> choice3;
}
}
I must have missed the fine print about throw; terminates the program instead of throwing a generic exception that can be caught by catch(...) In my implementation I would be satisfied with a single error message after catch. This will come in handy for some of the more complex exception handling I have on the horizon.