繁体   English   中英

如何在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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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