开发者

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

I am aware of a counter approach to开发者_高级运维 do this. I was wondering if there is a nice and compact way to do this.


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;
  }
}


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...


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


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜