3

我有以下安卓代码:

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 行之间的变量),但如果我不这样做,我就无法获得代码cursor在 finally 块中关闭。

在这种情况下该怎么办?忽略这个 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();
    }

In this case, the anomaly occurs with the distributeDate variable.

4

1 回答 1

2

The documentation is pretty easy to understand:

Either you use annotations to suppress warnings:

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

or you use a comment:

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

When it comes to your specific code, I'd say that the easiest way to handle it is to not use a finally block even though this would look like the perfect place for it.

于 2013-01-15T16:56:58.823 回答