即使有例外,希望程序继续继续

Want program to continue even when there is an exception

本文关键字:继续 希望 程序      更新时间:2023-10-16

我已经搜索了几次,但我有点没有找到我想要的东西。

我正在使用出色的处理(尝试/捕获(进行锻炼,在那里我发现了这个障碍。如果该程序发现例外,则终止了。

我尝试在 catch零件中调用函数,但仍终止。

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();
 }
}

这是类:

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<<"nn 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++;    
        }
   }
};

这是函数(我想调试时不完整(

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();
 }
}

在这里您看到我尝试在 catch零件中调用该函数,但仍然终止程序。我错过了一些基本的东西?还是还有其他解决方案/方法/逻辑?谢谢!

不可能从抛出C 异常的地方继续执行。C 例外不是为此而设计的。但是,如果发生例外,可以重复您要重复的代码:

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

请注意,在通常的情况下,如果发生例外,绝对没有做任何事情是一个坏主意。至少在某些日志文件中写下一些东西。