2011-08-31 37 views
1

我有這個代碼塊FindBugs的 - 「close()方法調用上,始終是空值」

是FindBugs的/聲納報告由

Correctness - close() invoked on a value that is always null 
close() is being invoked on a value that is always null. If this statement 
is executed, a null pointer exception will occur. But the big risk here you 
never close something that should be closed. 
Key: NP_CLOSING_NULL 

,但如果你折磨

private void doSomething(Properties properties) throws XXException 
{ 
    PersistenceManager pm = null;   

    try { 
     pm = new PersistenceManager(distributedDatabase, "PeriodHelper: insertPeriod"); 

     try { 
      pm.create(Tables.MY_TABLE); 
     } catch (ObjectAlreadyExistsException e) { 
      logger.warn("Could not create table! - "+e.getMessage(), e); 
      return; 
     } 

     pm.commit(); 
     return; 
    } 
    catch (Exception e) { 
     throw new XXException(e.getMessage(), e); 
    } 
    finally { 
     if (pm != null) 
      pm.close(); 
    } 
} 

查看代碼,調用close()方法時的pm對象將始終不爲null。任何人都可以解釋爲什麼findbugs得到這個錯誤?

+1

你可以在finally子句之前和之內顯示代碼嗎? – home

+2

你有超過30個問題沒有被接受的答案。也許你可以回顧一下老問題,看看有沒有可以接受的答案。 –

+1

您的錯誤位於代碼的第42行。如果不是明顯的**發佈代碼**,我們可以向您指出。 – rossum

回答

1

要麼 FindBugs的是完全錯誤的(不會是第一次)它知道pm不能爲非空位置(在這種情況下,將一種報告不正確的錯誤,它說「死代碼」或「條件總是假」)。

-1

你是否試圖用括號括起if語句?

if (pm!=null) {pm.close()}; 
+0

我不是在說這個,只是爲了說點什麼。有時候,Netbeans會抱怨一些東西,直到我添加大括號。而且我不會談論「If語句應該使用大括號」的建議...... –