如何在while循环中打破并继续try-catch?

时间:2015-08-05 00:30:53

标签: java while-loop ldap try-catch thread-sleep

需要在try-catch中使用Java使用LDAP连接来连接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语句位于循环中的正确位置。

1 个答案:

答案 0 :(得分:1)

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