I am looking for a way to get the logic of retrying an operation in a single method while keeping the exception types of the operation.
I.e., the implementation to retry an operation could look like this:
public void retriedOperation(Operable operable, int maxAttempts) throws Exception {
for (int attempt = 0; attempt < maxAttempts; attempt++) {
try {
operable.doOperation();
break;
} catch (Exception e) {
if (attempt + 1 > maxAttempts) {
throw e;
}
}
}
}
This implementation is however only capable of throwing an unspecified Exception
and thereby looses lots of information.
Unfortunately, generic Exceptions can neither be caught nor thrown not be caught in Java, thus something like
public void <ExceptionType extends Exception> retriedOperation(...) throws ExceptionType { ... }
would only allow to catch an unspecific Exception, check if it is of the right type and then cast it. But if it is of another type, it cannot be thrown with this method header.
Is there a way to implement a generic retry function that preserves specific exceptions?