gpt4 book ai didi

java - Java中如何处理超时异常?

转载 作者:行者123 更新时间:2023-11-29 05:52:09 32 4
gpt4 key购买 nike

这是我的代码:

 private void synCampaign() {
List<Campaign> campaigns;
try {
campaigns = AdwordsCampaign.getAllCampaign();
for(Campaign c : campaigns)
CampaignDao.save(c);
} catch (ApiException e) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synCampaign();
e.printStackTrace();
} catch (RemoteException e) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synCampaign();
e.printStackTrace();
}

}

AdwordsCampaign.getAllCampaign() 尝试获取一些远程资源。这可能会抛出 RemoteException,因为 Internet 连接超时。当异常被捕获时,我只想让线程 hibernate 一会儿,然后再尝试获取远程资源。

我的代码有问题吗?或者有更好的方法吗?

最佳答案

没什么不对,但是(可能是无限的)递归重试循环(和堆栈增长)让我有点紧张。我会这样写:

private void synCampaignWithRetries(int ntries, int msecsRetry) {
while(ntries-- >=0 ) {
try {
synCampaign();
return; // no exception? success
}
catch (ApiException e ) {
// log exception?
}
catch (RemoteException e ) {
// log exception?
}
try {
Thread.sleep(msecsRetry);
} catch (InterruptedException e1) {
// log exception?
}
}
// no success , even with ntries - log?
}

private void synCampaign() throws ApiException ,RemoteException {
List<Campaign> campaigns = AdwordsCampaign.getAllCampaign();
for(Campaign c : campaigns)
CampaignDao.save(c);
}

关于java - Java中如何处理超时异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13465930/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com