我想为我的Android应用程序提供异常处理策略(尽管这也可能适用于任何Java应用程序)。例如,我在这个例子中记事本应用程序看删除()函数的ContentProvider:需要帮助了解在Android中处理异常的位置
public int delete(Uri uri, String where, String[] whereArgs) {
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;
}
发生什么情况,如果Uri
是空?或getContext
()?或getContentresolver
()?
我得出结论,ContentResolver
不是捕捉异常的地方,但它应该重新抛出它们或抛出新的异常,以便应用程序可以显示有意义的错误消息。
以下或类似的东西会不会是一个坏的方法(矫枉过正) - 我是否应该让NullPointerException
s等泡到顶端,以更通用的方式处理(按照示例)?
public int delete(Uri uri, String where, String[] whereArgs)
throws SQLiteException, IllegalArgumentException, NotifyException {
if (null != mOpenHelper) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
if (null != db) {
if (null != uri) {
int count = 0;
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);
}
if (null != getContext()) && (null != getContentResolver()) {
getContext().getContentResolver().notifyChange(uri, null);
} else {
throw NotifyException("Failed to notify change");
}
return count;
} else {
throw new IllegalArgumentException("Must provide URI");
}
} else {
throw new SQLiteException("Failed to get database");
}
} else {
throw new SQLiteException("Invalid database helper");
}
}
声明:此代码可能无法编译!这是一个例子。
这当然更难读!我不知道什么是正确的平衡,需要一些帮助!
更新:我通读了Android的推荐做法(请参阅http://source.android.com/source/code-style.html#java-language-rules),但它让我更加困惑!