1

我正在尝试进行可能由于服务器关闭而引发异常的调用。这就是我想要完成的:

Server server = serverQueue.poll();
try {
     if (server==null){return null}
     server.makeConnection();

} catch (Exception e) {
     // try another server
     server = serverQueue.poll();
     // now return to try block?

}

所以我有 5 台服务器,也许在后期我会添加更多。所以我想以这种方式与他们中的任何人联系。我怎样才能返回到 try 块?java中有没有像下面这样的语句?:

Server server = serverQueue.poll();
outerBlock:
try {
     if (server==null){return null}
     server.makeConnection();

} catch (Exception e) {
     // try another server
     server = serverQueue.poll();
     continue outerBlock;

}
4

3 回答 3

0

基本上是一个循环:

Server server = serverQueue.poll();
boolean connected = false;
while (!connected) {
    if (server == null) {
        return null;
    }
    try {
         server.makeConnection();
         connected = true;
    } catch (Exception e) {
         // Presumably log something here, for management info

         // try another server
         server = serverQueue.poll();
    }
}

或者为了避免重复:

Server server;
boolean connected = false;
while (!connected) {
    server = serverQueue.poll();
    if (server == null) {
        return null;
    }
    try {
         server.makeConnection();
         connected = true;
    } catch (Exception e) {
         // Presumably log something here, for management info
    }
}

您可能会考虑将其中的“查找服务器”部分隔离到它自己的功能中。

于 2012-06-27T01:02:07.200 回答
0

你可以使用 for 循环

 Server server;     

for(int i=0;i<=numberOFServers-1;i++){
   server = serverQueue.poll();
      try {
           if (server==null){return null}
           server.makeConnection();

          } catch (Exception e) {

             System.out.println("Server : " +i+ " could not establish connection");
          }
 }
于 2012-06-27T01:02:33.027 回答
0

你需要把你的try块放在一个简单的循环中,要么while要么for.

于 2012-06-27T00:56:02.193 回答