IllegalStateException
如果我正在执行一段需要许多变量不为空的代码,例如在delete()
我拥有的内容提供程序函数中,那么在我的 Android 应用程序中抛出一个对我来说是否有效:
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
?我想这样做的原因是因为对我来说这个函数只是 throw 似乎是错误的NullPointerExceptions
?