Alex Rivera | Logout

How do you implement a re-try-catch?

Asked 2012-11-05T20:36:54.607
268

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.

Edit
Report

1 Answer

7

Use a while loop with local status flag. Initialize the flag as false and set it to true when operation is successful e.g. below:

boolean success  = false;
while(!success){
   try{ 
       some_instruction(); 
       success = true;
   } catch (NearlyUnexpectedException e){
     fix_the_problem();
   }
}

This will keep retrying until its successful.

If you want to retry only certain number of times then use a counter as well:

boolean success  = false;
int count = 0, MAX_TRIES = 10;
while(!success && count++ < MAX_TRIES){
   try{ 
       some_instruction(); 
       success = true;
   } catch (NearlyUnexpectedException e){
     fix_the_problem();
   }
}
if(!success){
  //It wasn't successful after 10 retries
}

This will try max 10 times if not successful until then an will exit if its successful before hand.

answered 2012-11-05T20:39:39.610

Your Answer