2013-01-15 102 views
3

我有以下的Android代码:PMD规则:如何妥善解决这个DD-异常问题

public final List<MyObj> getList() { 
    Cursor cursor = null; 
    try { 
     final String queryStr = GET_LIST_STATEMENT; 
     cursor = db.rawQuery(queryStr, new String[] {}); 
     List<MyObj> list = null; 
     //here I get the data from de cursor. 
     return list ; 
    } catch (SQLiteFullException ex) { 
     //do something to treat the exception. 
    } finally { 
     if (cursor != null) { 
      cursor.close(); 
     } 
    } 
} 

当我运行了这个代码PMD分析,我得到了以下问题:Found 'DD'-anomaly for variable 'cursor' (lines '182'-'185').

  • 182行是:Cursor cursor = null;
  • 行185:cursor = db.rawQuery(queryStr, new String[] {});

所以,我明白,问题是,我在该行182做过早初始化(我从来不看线182和185之间的变量),但如果我不这样做,我不能让代码在finally块中关闭cursor

怎么在这种情况下怎么办?只要忽略这个PMD问题?我可以配置PMD不会引发这种特定类型的DD异常(并非所有的DD异常)吗? PMD是否应该足够聪明,不会引发这个问题?

,我认为是不是一个真正的问题DD-异常又如:

Date distributeDate; 
    try { 
     distributeDate = mDf.parse(someStringDate); 
    } catch (ParseException e) { 
     Log.e("Problem", "Problem parsing the date of the education. Apply default date."); 
     distributeDate = Calendar.getInstance().getTime(); 
    } 

在这种情况下,异常与​​distributeDate变量发生。

回答

2

documentation是很容易理解的:

要么你使用注解抑制警告:

// This will suppress UnusedLocalVariable warnings in this class 
@SuppressWarnings("PMD.UnusedLocalVariable") 
public class Bar { 
void bar() { 
    int foo; 
} 
} 

,或者你使用注释:

public class Bar { 
// 'bar' is accessed by a native method, so we want to suppress warnings for it 
private int bar; //NOPMD 
} 

当涉及到您的特定代码,我想说处理它的最简单的方法是不使用finally块,尽管这看起来像是一个完美的地方。