如何处理Java中的超时异常?

时间:2012-11-20 02:55:59

标签: java timeout

这是我的代码:

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

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

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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();
    }

答案 2 :(得分: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
        }