如果我正在執行一個代碼塊,要求大量變量不爲空,例如在我的Android應用程序中拋出IllegalStateException
,在內容提供商delete()
功能我:Android和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
?
就我個人而言,我更喜歡NPE的全堆棧跟蹤,所以我知道是什麼造成它。如果你想隱藏用戶的實現,但是當某些事情失敗時仍然會回傳,我會主動檢查null或無效的參數,然後用無效的參數拋出異常,並提供其他有用的信息。 –
例如,如果調用者是一個活動:你會嘗試{getContentResolver()。delete(myUri,myWhere,myWhereArgs); } catch(NullPointerException e){//使用e做東西}? – Mewzer
'db',''getContext()'和'getContentResolver()'不能返回null,'mOpenHelper'這是對你自己類的引用,如果你正確的話我不會看到它是'null'在提供者中實例化它。 – Luksprog