Legend
Legend

Reputation: 116810

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.

Upvotes: 18

Views: 19636

Answers (4)

yegor256
yegor256

Reputation: 105053

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

Upvotes: 1

oxbow_lakes
oxbow_lakes

Reputation: 134270

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

Upvotes: 31

Legend
Legend

Reputation: 116810

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

Upvotes: 6

abalogh
abalogh

Reputation: 8281

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

Upvotes: 2

Related Questions