Programs & Examples
Exception Handling · Study material
Retry with back-off for flaky services
A generic retry helper catches only the transient exception type, waits longer each time and, when it gives up, throws a new exception that keeps the last failure as its cause.
import java.util.function.Supplier;
class TransientException extends RuntimeException {
private static final long serialVersionUID = 1L;
TransientException(String m) { super(m); }
}
public class Main {
static <T> T retry(Supplier<T> action, int maxAttempts) {
RuntimeException last = null;
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
T result = action.get();
System.out.println(" attempt " + attempt + " succeeded");
return result;
} catch (TransientException e) {
last = e;
System.out.println(" attempt " + attempt + " failed: " + e.getMessage() + ", waiting " + (100 << (attempt - 1)) + " ms");
}
}
throw new IllegalStateException("gave up after " + maxAttempts + " attempts", last);
}
public static void main(String[] args) {
int[] calls = {0};
System.out.println("payment API:");
String r = retry(() -> {
if (++calls[0] < 3) throw new TransientException("timeout");
return "PAID";
}, 5);
System.out.println("result " + r);
System.out.println("sms API:");
try {
retry(() -> { throw new TransientException("503"); }, 3);
} catch (IllegalStateException e) {
System.out.println(e.getMessage() + " (last error: " + e.getCause().getMessage() + ")");
}
}
}
payment API: attempt 1 failed: timeout, waiting 100 ms attempt 2 failed: timeout, waiting 200 ms attempt 3 succeeded result PAID sms API: attempt 1 failed: 503, waiting 100 ms attempt 2 failed: 503, waiting 200 ms attempt 3 failed: 503, waiting 400 ms gave up after 3 attempts (last error: 503)
Custom checked and unchecked exceptions
The bank example defines InsufficientFundsException (checked) and AccountFrozenException (unchecked) and handles both.
Automatic resource clean-up
The try-with-resources example opens two connections and shows they are closed in reverse order even when a query fails.