Want program to continue even when there is an exception

假装没事ソ 提交于 2020-01-11 14:43:50

问题


I have searched a few times but I kinda, didnt found what i exactly wanted.

I was working out with exceptional handling (try/catch), where i found this obstacle. If the program finds an exception, it terminated whatsoever.

I tried calling a function in the catch part, but it still terminates.

void exception_handle() //This is for handling exception if user inputs a char instead of int//
{
user_play uplay;
try
 {
    uplay.usersentry();
 }
catch(std::runtime_error& e)
 {
    cout<<"Input a string bro, not a character"<<endl;
    user_input();
 }
}

Here is the class:

class user_play //this class is for letting user play the game by allowing them to enter desired number in the desired empty space//
{
 public:
 void usersentry()
  {
    int tempdata;
    retry:
     cout<<"\n\n Enter the row and coloumn where you want to enter data"<<endl;
     cin>>i>>j;
        if (i>=1 && i<=9 && j>=1 && j<=9)
        {
            cout<<"\n Enter your desired value to put in that place"<<endl;
            cin>>tempdata;
            if(tempdata>=1 && tempdata<=9)
            {
                data=tempdata;
            }
            else
            {
                throw std::runtime_error("Soduku contains numbers from 1 to 9 only.Please try again");
                loops++;
            }
        }
        else
        {
            throw std::runtime_error("Soduku row exists between 1 and 9 only.Please try again");
            loops++;    
        }
   }
};

Here is the function(It's incomplete as i am trying to debugg)

int user_input() //this one is for taking correct value from user and storing it in its respective place//
{
a=0;
//Object Declaration//
rowrules rr;
columnrules cr;

//for handling the program exceptions
exception_handle();

//rules for row and column
//rr.rrules();
//cr.crules();
//ruleselect();
//i--;
//j--;
if(a==0)
{
    soduku[i-1][j-1]=data;
  return soduku[i-1][j-1];
}
else
 {
    user_input();
 }
}

here as you see i tried calling the function in catch part but still the program terminated.Am I missing something basic?? Or is there any other solution/method/logic? Thanks!


回答1:


It is not possible to continue execution from the place where C++ exception is thrown. C++ exceptions are not designed for that. But it is possible to repeat the code you want repeated if the exception happens:

for (bool success = false; !success; )
{
    try
    {
        <some code that should be repeated if exception happens>

        success = true;
    }
    catch (...)
    {
    }
}

Note that in general case it is a bad idea to do absolutely nothing if exception happens. At least write something down in some log file, if you have it.



来源:https://stackoverflow.com/questions/44369211/want-program-to-continue-even-when-there-is-an-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!