Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在while循环中中断并继续尝试捕获?_Java_While Loop_Ldap_Try Catch_Thread Sleep - Fatal编程技术网

Java 如何在while循环中中断并继续尝试捕获?

Java 如何在while循环中中断并继续尝试捕获?,java,while-loop,ldap,try-catch,thread-sleep,Java,While Loop,Ldap,Try Catch,Thread Sleep,在一个try-catch中,需要使用Java的LDAPConnection连接到LDAP。当无法建立初始连接时,我现在想创建一些逻辑,在1分钟后重新尝试连接,最多尝试3次 当前逻辑: try { connect = new LDAPConnection(...); } catch (LDAPException exc) { //throw exception message } 所需逻辑: int maxAttempts = 3, attempts=0; while(a

在一个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++;
}
int最大尝试次数=3,尝试次数=0;
while(尝试<最大尝试){
试一试{
connect=新的LDAPConnection(…);
/*若可以建立连接,那个么从循环中断,但保持连接活动*/
打破
}捕获(LDAPException exc){
如果(尝试==(最大尝试-1)){
//抛出异常消息
}
继续;
}
睡眠(1000);
尝试++;
}

我想要的逻辑中的代码正确吗?我还想确保我的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);
}
int最大尝试次数=3;
for(int尝试次数=0;尝试次数<最大尝试次数;尝试次数++){
试一试{
connect=新的LDAPConnection(…);
/*若可以建立连接,那个么从循环中断,但保持连接活动*/
打破
}捕获(LDAPException exc){
如果(尝试==(最大尝试-1)){
//抛出异常消息
抛出exc;
}
}
睡眠(1000);
}

删除“继续”,否则您将有无限次的尝试-因为您从未尝试过“尝试++”