希望程序即使有异常也能继续 [英] Want program to continue even when there is an exception
问题描述
我搜索了几次,但我还没找到我真正想要的东西。
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.
我尝试在 catch
部分调用一个函数,但是
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();
}
}
这是课程:
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();
}
}
在这里您看到我尝试在 catch
部分,但程序仍然终止。我缺少基本内容吗?还是有其他解决方案/方法/逻辑?
谢谢!
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!
推荐答案
无法从引发C ++异常的地方继续执行。 C ++异常不是为此而设计的。但是,如果发生异常,则可以重复您要重复的代码:
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.
这篇关于希望程序即使有异常也能继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!