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

后端 未结 4 2037
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-14 20:00

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

相关标签:
4条回答
  • 2020-12-14 20:36

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

    0 讨论(0)
  • 2020-12-14 20:46

    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

    0 讨论(0)
  • 2020-12-14 20:48

    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;
      }
    }
    
    0 讨论(0)
  • 2020-12-14 20:53

    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 讨论(0)
提交回复
热议问题