I've entered in an argument with a fellow colleague about a piece of code. While he thinks that it is ok, I don't. But I don't have any more arguments than that calling the same method (recursion) in a catch block is not a good practice.
So here is a pseudocode of what we are arguing about:
public String someMethod( SomeType param1, SomeType param2 ..., int attempts ){
int max_attempts = 5;
try{
//doSomething here;
return result;
}catch (Exception e){
if ( attempts == max_attempts ){
throw new RuntimeException(e);
}
//log exception
//sleep for some time
//here is the part I do not agree.
return someMethod( param1, param2 ..., attempts+1 );
}
}
My suggestion is to have a structure like this one:
public String someMethod( SomeType param1, SomeType param2... )
throws Exception /*or whatever*/{
//do something
return result;
}
public String executeProcess( SomeType param1, SomeType param2 ... ){
int attempts = 0;
boolean ok = false;
String result;
do{
try{
result = someMethod( param1, param2... );
ok=true;
}catch( /*specific exceptions here*/ e ){
attempts++;
//log exception
//sleep for some time
}
}while( !ok || attempts<5 ); //just to be clear 5 here would be a constant
if ( attempts >= 5 ){
throw new RuntimeException(e);
}
return result;
}
In my solution could even evolve into something even more elegant like an executor class with a process list and priority, etc. (of course only if needed).
So which one of these is the best course of action and what would be the arguments to defend it (pros and cons).
What the someMethod
does is to create a HttpURLConnection
and send a POST
request to a webservice that will return a JSON
string which will then be handled and converted to an object outside the context of this method (the conversion part).
All exception handling will be based on the connection with the webservice.
What I forgot to mention here is that his version of the code has already been in production for a long time, therefore there aren't any "programming bugs". The only exceptions that have been thrown are ones concerning the connection/timeouts (whatever) related to the webservice.
I even talked to him to go the log (history) file and get all specific exceptions and put in the catch block.
Considering that the exceptions that have been handled will be the specific ones, what would be the best solution?
someMethod
returnsnull
to indicate failure so your looping code can be much simpler.someMethod