2012-11-20 81 views
1

這裏是我的代碼:如何處理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因爲互聯網連接超時。當發現異常時,我只想讓線程休眠一段時間,然後嘗試再次獲取遠程資源。

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

+0

您的代碼是否工作?或者你只是問,你這樣做的方式可以嗎? – Clark

+0

我只是覺得我的代碼有點奇怪,所以我想確保我做的方式沒問題。 @Clark –

+0

爲了解決infgoax提到的問題,我需要一個作業調度程序類? @Yogendra Singh –

回答

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

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