Well, I’m studying for an exam so I tried to keep my code as simple as possible, but then something very weird happened: the exercise was to change the following code and, by using exceptions, get back to the main menu.
Here’s the code of the question:
void ha_ha_loop()
{
int i, c;
while(1)
{
for(i=0; i < 3; i++)
{
cout << "Ha Ha Ha" << endl;
sleep(3);
} // for
ask_return();
} // while
} // ha_ha_loop
void dollar_loop()
{
int i;
while(1)
{
for(i=0; i < 3; i++)
{
cout << "$$$$$$$$$ " << endl;
sleep(3);
} // for
ask_return();
} /* while */
} // dollar_loop
void mainloop()
{
string answer;
while (1)
{
cout << "Press 1 for Ha Ha Ha." << endl;
cout << "Press 2 for $$$$$$$$." << endl;
cout << "Press 3 for to quit." << endl;
cin >> answer;
switch (answer[0])
{
case '1':
ha_ha_loop();
case '2':
dollar_loop();
case '3':
return;
} // switch
} // while
} // mainloop
And what I did was:
void ask_return() {
char c;
cout << "Return to main menu? y/n:"<<endl;
cin >> c;
if (c=='y') throw 1;
}
void ha_ha_loop()
{
int i, c;
while(1)
{
for(i=0; i < 3; i++)
{
cout << "Ha Ha Ha" << endl;
} // for
ask_return();
} // while
} // ha_ha_loop
void dollar_loop()
{
int i;
while(1)
{
for(i=0; i < 3; i++)
{
cout << "$$$$$$$$$ " << endl;
} // for
ask_return();
} /* while */
} // dollar_loop
void mainloop()
{
char answer;
while (1)
{
cout << "Press 1 for Ha Ha Ha." << endl;
cout << "Press 2 for $$$$$$$$." << endl;
cout << "Press 3 for to quit." << endl;
cin >> answer;
switch (answer)
{
case '1':
ha_ha_loop();
case '2':
dollar_loop();
case '3':
return;
}
}
}
int main() {
try {
mainloop();
} catch (...) {
mainloop();
}
}
It works fine at the beginning, but then after one time it terminates my program with an unhandled exception message. Why?
What is the simplest correct way to do that?
Edit:
this is a working way :
void ask_return() {
char c;
cout << "Return to main menu? y/n:"<<endl;
cin >> c;
if (c=='y') throw 1;
}
void ha_ha_loop()
{
int i, c;
while(1)
{
for(i=0; i < 3; i++)
{
cout << "Ha Ha Ha" << endl;
} // for
ask_return();
} // while
} // ha_ha_loop
void dollar_loop()
{
int i;
while(1)
{
for(i=0; i < 3; i++)
{
cout << "$$$$$$$$$ " << endl;
} // for
ask_return();
} /* while */
} // dollar_loop
void mainloop()
{
char answer;
while (1)
{
try {
cout << "Press 1 for Ha Ha Ha." << endl;
cout << "Press 2 for $$$$$$$$." << endl;
cout << "Press 3 for to quit." << endl;
cin >> answer;
switch (answer)
{
case '1':
ha_ha_loop();
case '2':
dollar_loop();
case '3':
return;
}
} catch (...) {
}
}
}
int main() {
mainloop();
}
I’ll only answer the “how come” part, since the simplest correct way is what you’re supposed to solve yourself. When you do
you execute
mainloop, catching any exceptions. When an exception is caught, the handler executesmainloopagain, outside of atryblock. You’ll want to repeatedly go intomainloop, catching the exception every time.