需要在try-catch中使用Java使用LDAPConnection连接到LDAP。当无法建立初始连接时,我现在想创建一些逻辑以在1分钟后重新尝试连接,最多3次尝试。

当前逻辑:

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


所需逻辑:

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


我期望的逻辑中的代码正确吗?我还想确保我的break和Continue语句在循环中的正确位置。

最佳答案

摆脱continue以避免无限循环。
并且由于您有一个计数器,所以请使用for循环而不是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);
}

09-10 01:42