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 range 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++
The C programming language does not support exception handling nor error handling. It is an additional feature offered by C. In spite of the absence of this feature, there are certain ways to implement error handling in C. Generally, in case of an error, most of the functions either return a null value or -1.
The try-except statement is a Microsoft extension to the C language that enables applications to gain control of a program when events that normally terminate execution occur. Such events are called exceptions, and the mechanism that deals with exceptions is called structured exception handling.
Basically, the computer will try to execute code in the try block. If it doesn't work, the computer will execute the code in the catch block. After executing code from either the try or the catch block the computer will run the rest of the code as normal.
To ignore an exception in Java, you need to add the try... catch block to the code that can throw an exception, but you don't need to write anything inside the catch block.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With