Try-catch is meant to help in the exception handling. This means somehow that it will help our system to be more robust: try to recover from an unexpected event.
We suspect something might happen when executing and instruction (sending a message), so it gets enclosed in the try. If that something nearly unexpected happens, we can do something: we write the catch. I don't think we called to just log the exception. I thing the catch block is meant to give us the opportunity of recovering from the error.
Now, let's say we recover from the error because we could fix what was wrong. It could be super nice to do a re-try:
try{ some_instruction(); }
catch (NearlyUnexpectedException e){
fix_the_problem();
retry;
}
This would quickly fall in the eternal loop, but let's say that the fix_the_problem returns true, then we retry. Given that there is no such thing in Java, how would YOU solve this problem? What would be your best design code for solving this?
This is like a philosophical question, given that I already know what I'm asking for is not directly supported by Java.
You need to enclose your
try-catch
inside awhile
loop like this: -I have taken
count
andmaxTries
to avoid running into an infinite loop, in case the exception keeps on occurring in yourtry block
.Use a do-while to design re-try block.
As usual, the best design depends on the particular circumstances. Usually though, I write something like:
In case it's useful, a couple more options to consider, all thrown together (stopfile instead of retries, sleep, continue larger loop) all possibly helpful.
following is my solution with very simple approach!
A simple way to solve the issue would be to wrap the try/catch in a while loop and maintain a count. This way you could prevent an infinite loop by checking a count against some other variable while maintaining a log of your failures. It isn't the most exquisite solution, but it would work.