I am aware of a counter approach to do this. I was wondering if there is a nice and compact way to do this.
If you have try catch within the loop it gets executed completely inspite of exceptions.
The try...catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With