Java: How would I write a try-catch-repeat block?

2020-02-08 17:26发布

问题:

I am aware of a counter approach to do this. I was wondering if there is a nice and compact way to do this.

回答1:

Legend - your answer could be improved upon; because if you fail numTries times, you swallow the exception. Much better:

while (true) {
  try {
    //
    break;
  } catch (Exception e ) {
    if (--numTries == 0) throw e;
  }
}


回答2:

I have seen a few approaches but I use the following:

int numtries = 3;
while(numtries-- != 0)
   try {
        ...
        break;
   } catch(Exception e) {
        continue;
   }
}

This might not be the best approach though. If you have any other suggestions, please put them here.

EDIT: A better approach was suggested by oxbow_lakes. Please take a look at that...



回答3:

if you are using Spring already, you might want to create an aspect for this behavior as it is a cross-cutting concern and all you need to create is a pointcut that matches all your methods that need the functionality. see http://static.springsource.org/spring/docs/2.5.x/reference/aop.html#aop-ataspectj-example



回答4:

Try aspect oriented programming and @RetryOnFailure annotation from jcabi-aspects:

@RetryOnFailure(attempts = 2, delay = 10, verbose = false)
public String load(URL url) {
  return url.openConnection().getContent();
}