I was trying to have a handleException
method, which can take an exception object and a list of acceptable exception classes to check if the exception is acceptable and can be retried.
void handleException(Exception e, String... acceptableExceptionNames)
throws MyException {
boolean isRetryable = false;
for(String acceptableExceptionName: acceptableExceptionNames) {
try {
if (Class.forName(acceptableExceptionName).isInstance(e)) {
isRetryable = true;
break;
}
} catch (ClassNotFoundException e1) {
continue;
}
}
if (isRetryable) {
// log retryable
} else {
// log error
}
throw new MyException(isRetryable, "Failed");
}
The parameter I pass in is a String... classNames
instead of Class<? extends Exception> classes
, because if I do something like this:
void handleException(
Exception e,
Class<? extends Exception>... acceptableExceptions)
throws MyException {
for (Class acceptableException : acceptableExceptions) {
if (e instanceOf acceptableException) {}
}
}
The IDE will complain about unknown class acceptableException
Anyone knows if there's a way to pass Class<?>
? Or a better way to avoid using String classNames
and Class.forName()
?