簡體   English   中英

如何處理Java中的超時異常?

[英]How to deal with timeout exception in Java?

這是我的代碼:

 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連接超時。 捕獲異常時,我只想讓線程暫停一段時間,然后嘗試再次獲取遠程資源。

我的代碼有問題嗎? 或者,還有更好的方法?

沒有什么是錯的,但是帶有遞歸(和堆棧增長)的(可能是無限的)重試循環讓我有點緊張。 我寫的是:

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);
}

除了重復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();
    }

你確實無法將其作為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
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM