How do you implement a re-try-catch?
You need to enclose your try-catch
inside a while
loop like this: -
int count = 0;int maxTries = 3;while(true) { try { // Some Code // break out of loop, or return, on success } catch (SomeException e) { // handle exception if (++count == maxTries) throw e; }}
I have taken count
and maxTries
to avoid running into an infinite loop, in case the exception keeps on occurring in your try block
.
Obligatory "enterprisy" solution:
public abstract class Operation { abstract public void doIt(); public void handleException(Exception cause) { //default impl: do nothing, log the exception, etc. }}public class OperationHelper { public static void doWithRetry(int maxAttempts, Operation operation) { for (int count = 0; count < maxAttempts; count++) { try { operation.doIt(); count = maxAttempts; //don't retry } catch (Exception e) { operation.handleException(e); } } }}
And to call:
OperationHelper.doWithRetry(5, new Operation() { @Override public void doIt() { //do some stuff } @Override public void handleException(Exception cause) { //recover from the Exception }});
As usual, the best design depends on the particular circumstances. Usually though, I write something like:
for (int retries = 0;; retries++) { try { return doSomething(); } catch (SomeException e) { if (retries < 6) { continue; } else { throw e; } }}