views:

511

answers:

3

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

+3  A: 

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

Legend
This message belongs in your own topicstart..
BalusC
This was meant to be one of those answer your own question :) with the hope that it will help others...
Legend
@Legend - I think if you look at my answer, you will see that your approach is flawed
oxbow_lakes
Updated my post... Thanks for input :)
Legend
+11  A: 

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;
  }
}
oxbow_lakes
+1  A: 

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

abalogh