2015-09-23 71 views
0

我目前正面臨着我的代碼問題,我無法弄清楚爲什麼這個語句正在評估它。這是我第一次使用finally塊,所以可能有一些基本的行爲我沒有理解。試試Catch Final - final在變量中總是爲空

這種方法所做的是從api獲取json文檔並將所述文檔存儲爲this.thisPage。然後另一種方法sliceItem將結果字段拆分爲json對象數組。

每當API返回具有不良字段的JSON(例如,將字符串字段存儲爲int或將int作爲double等)時,都會引發MalformedJsonException。這被嘗試了10次(由failsafeget處理),如果失敗10次,則拋出MalformedJsonException(RuntimeException)。我希望slicePage在這種情況下做的是獲得下一頁,而不是繼續這個頁面。爲了簡化這一點 - 每個頁面有100個條目;如果偏移3500被打破,我們希望得到偏移3600.

我目前面臨的問題是resp總是在最後的塊中計算到null。我不明白爲什麼會出現這種情況,因爲try塊可以返回非空值(JSONObject類型)。

任何幫助將不勝感激,如果你需要更多的信息/代碼,我願意提供。

public synchronized void slicePage(){ 
    JSONObject resp=null; // otherwise java complains that not initialised 
    ApiClient apiClient = new ApiClient(); 
    RestEndPoint pageUrl; 
    while (true) { 
     pageUrl = getNextPageEndPoint(); 
     if(pageUrl == null) { 
      throw new IllegalStateException("We have reached the end and the code isn't designed to handle the end here"); // we have reached the end 
     } 
     currentPageNumber++; 
     try { 
      resp = apiClient.failSafeGet(pageUrl, getRetryCount()); 
      break; 
     } 
     catch (MalformedJsonException e) { 
      logger.info(String.format("The json was still broken after %d retries. Skipping this page and notifying listeners", getRetryCount())); 
      for (Consumer<Integer> consumer: onSkipListenerList) { 
       consumer.accept(batchSize); // inform each listener that we are skipping this many entries 
      } 
     } 
     finally { // We need to set the next page end point no matter the outcome of the try catch. N.B. this gets executed even if there is a break 
      if(resp == null) { 
       // no next possible 
       setNextPageEndPoint(null); // don't consider next; we reached the max 
       this.thisPage = null; 
      } else { 
       if(currentPageNumber > maxPages - 1) { 
        // because a request has been made already, so reduce by 1 
        setNextPageEndPoint(null); // don't consider next; we reached the max 
       } else { 
        // else consider next page 
        setNextPageEndPoint(constructNextPageEndPoint(pageUrl, resp)); 
       } 
       this.thisPage = this.parseResult(resp); 

       setTotalCount(resp.getInt("totalResults")); 
      } 
     } 
    } 
} 

編輯我忘了提,當我說,它總是值爲空,我的意思是我的IDE - IntelliJ IDEA的,警告我說,如果條件計算結果始終爲null。以下是在Intellij中顯示的幫助(使用Ctrl-F1)。

Condition 'resp == null' is always 'true' less... (Ctrl+F1) 
This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations. 
Variables, method parameters and return values marked as @Nullable or @NotNull are treated as nullable (or not-null, respectively) and used during the analysis to check nullability contracts, e.g. report possible NullPointerException errors. 
More complex contracts can be defined using @Contract annotation, for example: 
@Contract("_, null -> null") — method returns null if its second argument is null @Contract("_, null -> null; _, !null -> !null") — method returns null if its second argument is null and not-null otherwise @Contract("true -> fail") — a typical assertFalse method which throws an exception if true is passed to it 
The inspection can be configured to use custom @Nullable 
@NotNull annotations (by default the ones from annotations.jar will be used) 

EDIT 2 事實證明,代碼分析是錯誤的,則該值爲非空運行一次。謝謝大家(包括評論員)分享您的見解和建議。最終,我在條件之前插入了一個logger.info,並且所有內容似乎都起作用。它似乎停止工作的原因是因爲圖形服務器正在運行超時。

+1

如果'resp'總是爲null,則表明'failSafeGet'總是拋出一個異常,或者它返回'null'。你有沒有隔離哪些發生?你是否在調試器中逐步瞭解代碼? –

+0

當我提到它總是'null'時,我並不清楚 - IDE說它總是評估爲null,但我在過去幾個月一直在使用這種方法。代碼的邏輯存在缺陷。謝謝大家對你的回答 –

+0

你的意思是「IDE說它總是評估爲空」?哪個IDE?你能寫一個簡短但完整的程序,表現出相同的行爲嗎? –

回答

0

這是正常行爲。此調用

apiClient.failSafeGet(pageUrl, getRetryCount()); 

拋出異常,因此該值賦值給resp永遠不會完成,因此在finally block值爲空。所以,無論你的方法總是拋出一個異常,或者,如果沒有,它在某個時刻返回null

0

在您的代碼:

try { 
      resp = apiClient.failSafeGet(pageUrl, getRetryCount()); 
      break; 
     } 
     catch (MalformedJsonException e) { 
      logger.info(String.format("The json was still broken after %d retries. Skipping this page and notifying listeners", getRetryCount())); 
      for (Consumer<Integer> consumer: onSkipListenerList) { 
       consumer.accept(batchSize); // inform each listener that we are skipping this many entries 
      } 
     } 
     finally {..... 

如果resp = apiClient.failSafeGet(pageUrl, getRetryCount());拋出一個異常,RESP將始終爲空,因爲程序assing的實例RESP之前失敗。

相關問題