【问题标题】:Android and IllegalStateExceptionAndroid 和 IllegalStateException
【发布时间】:2012-11-19 20:07:06
【问题描述】:

如果我正在执行需要多个变量不为空的代码块,例如,在我的 Android 应用程序中抛出 IllegalStateException 是否有效?在内容提供者delete() 函数中我有:

public int delete(Uri uri, String where, String[] whereArgs) {
    try {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
            case NOTES:
                count = db.delete(NOTES_TABLE_NAME, where, whereArgs);
                break;

            case NOTE_ID:
                String noteId = uri.getPathSegments().get(1);
                count = db.delete(NOTES_TABLE_NAME, NoteColumns._ID + "=" + noteId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
                break;

            default:
               throw new IllegalArgumentException("Unknown URI " + uri);
       }

       getContext().getContentResolver().notifyChange(uri, null);
       return count;

    } catch (NullPointerException e) {
       // We really shouldn't get any null pointers!
       throw new IllegalStateException();
    }
}

因为,虽然可能性很小,但以下变量可能为 NULL 的可能性很小:

- mOpenHelper
- db
- getContext()
- getContentResolver()

或者这是对IllegalStateException的滥用?我想这样做的原因是因为在我看来,这个函数只抛出 NullPointerExceptions 似乎是错误的?

【问题讨论】:

  • 就我个人而言,我更喜欢具有完整堆栈跟踪的 NPE,所以我知道是什么原因造成的。如果您想对用户隐藏实现,但在出现故障时仍会回复,我会主动检查 null 或无效参数,然后在无效参数中抛出异常,您可以提供任何其他有用的信息。
  • 所以例如,如果调用者是一个活动:你会放一个 try{ getContentResolver().delete(myUri, myWhere, myWhereArgs); } catch (NullPointerException e) { // 用 e 做点什么 }?
  • db, getContext() and getContentResolver() can't return null, mOpenHelper 这是对你自己的类的引用,我不明白它怎么可能是 null如果您在提供程序中正确实例化它。

标签: android exception-handling android-contentprovider illegalstateexception


【解决方案1】:

至少,使用throw new IllegalStateException(e); 来保留有关导致异常的原因的信息。

我个人会通过确保在我需要使用它们之前正确初始化所有必需的变量(mOpenHelper 等)来确保不会发生 NPE。

【讨论】:

  • 我同意 - 我正在努力确保 NPE 不会发生。但是,我想添加一个明确的检查以防万一(因为你永远不能说永远!)。
  • @Mewzer 我认为下一个问题确实是:如果您获得 NPE,您能否从中恢复?如果可以,抓住它并恢复,如果你不能让它冒泡并在最高级别抓住它,给出“意外错误blabla”。
  • 谢谢 - 在这种情况下,如果其中任何一个碰巧为空,那么我想它不可能恢复。
【解决方案2】:

为什么不创建自己的异常?

public class MyCustomException extends NullPointerException {

    private static final long serialVersionUID = 1L;

    public Exception innerException;

    public MyCustomException() {}

    public MyCustomException(Exception innerException) {
        this.innerException = innerException;
    }
}

...

if (mOpenHelper == null){thrown new MyCustomException("mOpenHelper is null!");}

或者,只是抓住 NPE,找出原因,然后抛出你自己的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多