简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM