Java >> Programma Java >  >> Java

Come si implementa un re-try-catch?

Devi allegare il tuo try-catch all'interno di un while loop in questo modo:-

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;
    }
}

Ho preso count e maxTries per evitare di incorrere in un ciclo infinito, nel caso in cui l'eccezione continui a verificarsi nel tuo try block .


Soluzione "impresa" obbligatoria:

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);
            }
        }
    }
}

E per chiamare:

OperationHelper.doWithRetry(5, new Operation() {
    @Override public void doIt() {
        //do some stuff
    }
    @Override public void handleException(Exception cause) {
        //recover from the Exception
    }
});

Come al solito, il miglior design dipende dalle circostanze particolari. Di solito, però, scrivo qualcosa come:

for (int retries = 0;; retries++) {
    try {
        return doSomething();
    } catch (SomeException e) {
        if (retries < 6) {
            continue;
        } else {
            throw e;
        }
    }
}

Etichetta Java