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

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

需要在 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);
}