簡體   English   中英

嘗試Catch Final-final變量始終為null

[英]Try Catch Final - final always has null in variable

我目前在我的代碼中遇到問題,無法弄清楚為什么此語句按原樣進行評估。 這是我第一次使用finally塊,因此可能存在一些我不了解的基本行為。

此方法的作用是從api獲取json文檔,並將該文檔存儲為this.thisPage 然后另一個方法sliceItem將結果字段拆分為json對象數組。

每當API返回包含錯誤字段的json(例如,將字符串字段存儲為int或將int存儲為double等)時,都會引發MalformedJsonException。 嘗試10次(由failsafeget處理),如果失敗10次,則拋出MalformedJsonException(RuntimeException)。 在這種情況下,我希望slicePage要做的是獲取下一頁而不是繼續此頁面。 為了簡化此操作-每個頁面有100個條目; 如果偏移量3500被破壞,我們要獲取偏移量3600。

我當前面臨的問題是,在最后一個塊中, resp總是評估為null 我不明白為什么會這樣,因為try塊可以返回除null(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警告我if條件總是評估為空。 以下是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)

編輯2事實證明,代碼分析是錯誤的,一旦運行該值將為非null。 感謝所有人(包括評論員)分享您的見解和建議。 最終,我在條件之前插入了logger.info,其值似乎一切正常。 它似乎停止工作的原因是圖形服務器已超時。

這是正常的行為。 這個電話

apiClient.failSafeGet(pageUrl, getRetryCount());

引發異常,因此對resp的值分配從未完成,因此在finally block該值為null。 因此,您的方法總是拋出異常,或者如果不是,則它在某個時刻返回null

在您的代碼中:

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始終為null,因為程序在實例實例化之前失敗。

暫無
暫無

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

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