【发布时间】: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()andgetContentResolver()can't returnnull,mOpenHelper这是对你自己的类的引用,我不明白它怎么可能是null如果您在提供程序中正确实例化它。
标签: android exception-handling android-contentprovider illegalstateexception