1

这是我的代码:

 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,因为互联网连接超时。当异常被捕获时,我只想让线程休眠一段时间,然后再次尝试获取远程资源。

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

4

3 回答 3

2

没有什么真正的问题,但是(可能是无限的)带有递归(以及堆栈增长)的重试循环让我有点紧张。我会写:

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);
}
于 2012-11-20T03:14:38.343 回答
1

这看起来不错,除了在 catch 块中重复代码(确保你想要的重试次数)。您可能希望创建一个私有方法来处理您的异常,如下所示:

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

    }

    private void waitAndSync(){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        synCampaign();
    }
于 2012-11-20T03:05:58.643 回答
0

您确实无法将其作为 SocketTimeoutException 捕获。可能的方法是捕获 RemoteException,检索它的原因并检查它是否是 SocketTimeoutException 的实例。

    try{
             // Your code that throws SocketTimeoutException

        }catch (RemoteException e) {
          if(e.getCause().getClass().equals(SocketTimeoutException.class)){
             System.out.println("It is SocketTimeoutException");
             // Do handling for socket exception
            }else{
              throw e;
            }
        }catch (Exception e) {
           // Handling other exception. If necessary
        }
于 2015-06-08T12:42:26.090 回答