Reputation: 1733
I have this code below and in this code, when the program have any exception occur, it retry the entire program. This seems to work fine. However, when there are million of methods in one single program, this seems a bit too much if it retries the entire program everytime it encounter exception.
What I am trying to say here is, let say I have 5 methods in a program, method 1, method 2, method 3, method 4, and method 5. If method 3 exception was found, it should only retry method 3 instead of retry the entire program. and similarly if the program occurs error in method 5, it should only retry the method 5.
Here is what I have so far. In this code, if either method 1, or 2, or 3 or 4 or 5 is detected, it will restart the entire program. I don't want that, I want to only retry wherever there is exception is found in the method. I am not sure how to fix this. Help will be appreciated. Some code for reference will be very helpful, thanks :)
Test.java
public class Test {
private static MAX_RETRIES = 3;
public static void main (String [] args) {
int retryAttempt = 1;
while (retryAttempt <= MAX_RETRIES) {
try{
method 1;
method 2;
method 3;
method 4;
method 5;
break;
}catch(Exception e){
e.printStackTrace();
retryAttempt ++;
if (retryAttempt == MAX_RETRIES){
//do something here
return;
}
}
}
}
}
Upvotes: 0
Views: 671
Reputation: 1498
You can create a boolean array indicating which methods are ok. With "ok", I mean "the method occurred without any problem". So, before you call "method 1", you check if(!isOk[1]) { method1(); isOk[1] = true;}
and the same for the others methods.
you can even do that:
instead of:
try{
method 1;
method 2;
method 3;
method 4;
method 5;
break;
}
you can do:
try{
if(!isOk[1]) {method1(); isOk[1] = true;}
if(!isOk[2]) {method2(); isOk[2] = true;}
if(!isOk[3]) {method3(); isOk[3] = true;}
if(!isOk[4]) {method4(); isOk[4] = true;}
if(!isOk[5]) {method5(); isOk[5] = true;}
break;
}
Of course, you'll have to create: boolean isOk[] = new boolean[6];
// or whatever is the method numbers.
Note: to be sure they are initially false, you can do that: for(int i = 0; i < 6; i++) isOk[i] = false;
Upvotes: 0
Reputation: 2363
You might want to have a look at @RetryOnFailure
of http://aspects.jcabi.com/.
Upvotes: 1