Search code examples
javawhile-loopldaptry-catchthread-sleep

How to break and continue a try-catch inside a while loop?


There is a need to connect to LDAP using LDAPConnection using Java in a try-catch. When the initial connection cannot be established, i now want to create some logic to reattempt the connection after 1 minute for a max of 3 attempts.

Current logic:

try {
      connect = new LDAPConnection(...);
} catch (LDAPException exc) {
      //throw exception message
}

Desired logic:

int maxAttempts = 3, attempts=0;
while(attempt < maxAttempts) {
     try {
         connect = new LDAPConnection(...);
         /*if connection can be established then break from loop, but keep connection alive*/
         break;
     } catch(LDAPException exc) {
            if(attempt == (maxAttempts-1)) {
                 //throw exception message
             }
             continue;
      }

     Thread.sleep(1000);
     attempt++;
}

Is the code in my desired logic correct? I also wanted to be sure my break and continue statements are in the correct location in the loop.


Solution

  • Get rid of the continue to avoid an infinite loop. And since you have a counter, use a for-loop instead of while:

    int maxAttempts = 3;
    for(int attempts = 0; attempts < maxAttempts; attempts++) {
        try {
             connect = new LDAPConnection(...);
             /*if connection can be established then break from loop, but keep connection alive*/
             break;
        } catch(LDAPException exc) {
             if(attempt == (maxAttempts-1)) {
                 //throw exception message
                 throw exc;
             }
        }
        Thread.sleep(1000);
    }