JAVA中while循环中如何初始化对象

问题描述 投票:0回答:1

我正在尝试初始化对象直到成功。代码工作正常,但在第一次实例/迭代中不起作用。有没有办法在 while 循环中初始化对象?

V1NamespaceList listOfns = null;

        try {
            listOfns = api.listNamespace(null, true, null, null, null, null, null, null, null, null);

        } catch (Exception e) {
            System.out.println("Something went wrong while fetching namespace list. Trying again ");
            while (listOfns != null)
            {
                listOfns = api.listNamespace(null, true, null, null, null, null, null, null, null, null);
    
            }
            
        }

我的目标尝试直到

listOfns
对象初始化成功。我怎样才能做到这一点? 请建议

java spring-boot
1个回答
0
投票

我建议在程序中添加重试次数。如果程序继续失败,您应该排除出现问题的原因。除非真的有特殊需要。

V1NamespaceList listOfNs = null;
int retryCount = 0;
final int MAX_RETRIES = 5; 
while (retryCount < MAX_RETRIES) {
    try {
        listOfNs = api.listNamespace(null, true, null, null, null, null, 
null, null, null, null);
        if (listOfNs != null) {
            break; 
        }
    } catch (Exception e) {
        System.out.println("Something went wrong while fetching namespace list. Trying again. Retry #" + (retryCount + 1));

    }
 retryCount++;

// can sleep for a while
 
//try {
//   Thread.sleep(1000);  
//} catch (InterruptedException ie) {
//    Thread.currentThread().interrupt();  
//}
   
}

if (listOfNs == null) {
    System.out.println("Failed to fetch namespace list after " + MAX_RETRIES + " attempts.");

// TODO

}
© www.soinside.com 2019 - 2024. All rights reserved.