Reputation: 613
have a following problem:
I have an abstract class with a method "call" that basically calls some otherMethod and if otherMethod throws an Exception I try to fix in catch by relogging and calling the "call" method again.
public Object call(String methodName, Object[] parameters, Class[] parameterTypes) throws RetryingException, RemoteException {
while (true) {
try {
return callMethod(methodName, parameters, parameterTypes);
} catch (SomeException e) {
if (numberOfTriesLeft-- == 0) {
throw new RetryingException();
}
login();
}
}
}
Now I have a subclass of this class with overriden method call that may take a null parameter. Basically if such situation happens I want to call the method from superclass, but the Exception mentioned above is not thrown, thus, no retry and method ends failing somewhere else. Is there a way to throw it manually and pass further or any other way to fix it? Thank you for your help!
@Override
public Object call(String methodName, Object[] parameters, Class[] parameterTypes) throws RetryingException, RemoteException {
if (parameters[0] == null){
// What to do here if I want to throw SomeException here to end up in a catch block from the call method in the superclass? Or how to change it
}
// Everything ok. No null params
...
return super.call(methodName, parameters, parameterTypes);
}
Upvotes: 0
Views: 1701
Reputation: 2170
From my experience, what you could do is to have a parent method like so:
public final Object call(String methodName, Object[] parameters, Class[] parameterTypes) throws RetryingException, RemoteException {
try {
callMethod(methodName, parameters, parameterTypes)
} catch (Exception ex) {
// Handle any exception here...
}
}
protected Object callMethod(String methodName, Object[] parameters, Class[] parameterTypes) throws RetryingException, RemoteException {
// .. your code
}
And then override the callMethod
(child) method instead:
@Override
protected Object callMethod(String methodName, Object[] parameters, Class[] parameterTypes) throws RetryingException, RemoteException {
// Exception thrown here will now be caught!
return super.callMethod(methodName, parameters, parameterTypes);
}
So this has separated the interface methods from the overrideable methods. I see this pattern quite a lot in existing APIs.
Some points:
call
is now final
stopping it from being overridden.callMethod
is protected
making it only override-able and callable from the same package - taking it out of the public API.Update: Taken on board the point provided by @Fildor.
Upvotes: 1