Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 512
Legend Avatar asked Nov 13 '09 19:11

Legend


People also ask

Can we write try catch inside for loop?

If you have try catch within the loop it gets executed completely inspite of exceptions.

Can we write try in catch block?

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.


2 Answers

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;
  }
}
like image 163
oxbow_lakes Avatar answered Sep 28 '22 23:09

oxbow_lakes


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

like image 39
Legend Avatar answered Sep 28 '22 23:09

Legend