2015-09-23 30 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之前失败。

相关问题