如果我正在执行一段需要多个变量非空的代码块,例如在内容提供程序delete()
函数中,我是否可以抛出一个IllegalStateException
异常?
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
是错误的。
db
、getContext()
和getContentResolver()
不能返回null
,mOpenHelper
是指向你自己的类的引用,如果在提供程序中正确实例化它,我不知道它怎么可能是null
。 - user