我正在尝试为我的 Android 应用程序提出异常处理策略(尽管这也可能适用于任何 Java 应用程序)。例如,我正在查看示例记事本应用程序中的 delete() ContentProvider 函数:
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 等冒泡到顶部以更通用的方式处理(根据示例)?.
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 ),但这让我更加困惑!
最佳答案
处理异常的想法是显示错误发生的明确原因,并可能根据错误执行某些操作。所以,请考虑:
定义您自己的从 Java 异常派生的异常类
将代码放入 try/catch block 中。当您捕获异常时,您可以使用跟踪记录它,然后抛出您自己的异常并提供清晰的解释。
在某些时候,您捕获自己的异常,提取信息并 在屏幕上显示信息,或者如果您提供 Web 服务,则将信息发送回程序用户
代码示例:
public class MyException extends Exception {
public static final String MYSeparator = "!@#!";
public MyException() {
super();
}
public MyException(String message) {
super(message);
}
public MyException(Throwable cause) {
super(cause);
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
public MyException(String errorCode, String errorDescription,
Throwable cause) {
super(errorCode + MYSeparator + errorDescription, cause);
}
public MyException(String errorCode, String errorDescription) {
super(errorCode + MYSeparator + errorDescription);
}
}
关于java - 需要帮助了解 Android 中处理异常的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13405263/