开发者

C++, ignore exception and continue code?

开发者 https://www.devze.com 2023-04-10 22:46 出处:网络
Is there a way allow execution of a bad block of code after an exception of thrown? Presently, my code has an while loop that runs continuously.The code inside this while loop sometimes throws a vect

Is there a way allow execution of a bad block of code after an exception of thrown?

Presently, my code has an while loop that runs continuously. The code inside this while loop sometimes throws a vector out of r开发者_如何学运维ange error. I have been unable to track down the cause of this particular exception, but ultimately, it doesn't matter much because the code inside the while loop does the same thing over and over again and the next iteration does not depend on the previous iteration in any way.

This, after the code within the while loop crashes, I would like it to start again from the top of the while statement.

Is there a way to accomplish this in C++? try/catch doesn't seem to work in this situation.

Additional Info: I would love to just take the code within the while loop, make it into its own executable, and put the while loop into a bash script, but there's some data each iteration requires that remains static and it takes too much time to re-load that data each time so I am forced to do my infinite while loop within C++


You just need to catch the exception inside the while loop:

while(true) 
{
    try 
    {
          // your code
    }
    catch (Exception e) { /* Please, at least do some logging or other error handling here*/ }
}   


The first thing that you should do is debug the code, for that you can probably run the code inside a debugger and diagnose what the problem is. Pushing the problem under the rug will not make it go away, and the program will still be buggy.

If on the other hand, the issue is with something that is truly exceptional but feasible (consider opening a file, sending a packet over the network, anything that could potentially fail, but is not expected to --as compared to something that should never happen), the try/catch approach should work.


if you could possibly post a snippet of code, we all could help you more. but in general you should always have some sort of error handling whether it be a try{}catch{} or just checking a variable like:

while(true)
{

if(flag == "Error")
{
//error handle
}

else
{
//continue with code execution
}

}

hope you get this problem solved!

0

精彩评论

暂无评论...
验证码 换一张
取 消