bog*_*dan 9 java android exception-handling try-catch
这段代码有什么问题?它不会捕获insertChild()
方法抛出的异常.
childDbOps.open();
try {
childDbOps.insertChild(child);
} catch (SQLiteException exception) {
Log.i("error la inserare child", "on the next line");
exception.printStackTrace();
} finally {
childDbOps.close();
}
Run Code Online (Sandbox Code Playgroud)
错误是:
ERROR/Database(320): android.database.sqlite.SQLiteConstraintException: error code 19:
constraint failed at com.android.dataLayer.DbAdapter.insertChild(DbAdapter.java:169)
at com.android.activities.ChildInsertActivity.onClick(ChildInsertActivity.java:203)
at android.view.View.performClick(View.java:2344)
Run Code Online (Sandbox Code Playgroud)
这是android sqlite.该行是在调用insert方法时.
小智 40
SQLiteDatabase.insert()方法用于您希望处理数据库写入而不会在写入失败时展开堆栈的情况.如果要在插入数据库时捕获异常,请使用[SQLite.insertOrThrow(] [1])方法.它将抛出一个异常,然后您可以捕获并处理它.
[1]:http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insertOrThrow (java.lang.String,java.lang.String,android.content.ContentValues)
您只捕获类型的异常SQLiteException
。如果该insertChild
方法抛出任何其他异常,则不会被捕获。
try {
childDbOps.insertChild(child);
}
catch(SQLiteException exception) {
Log.i("error la inserare child", "on the next line");
exception.printStackTrace();
}
catch(AnotherException exception) {
//handle it
}
//Catch them all here
catch(Exception exception) {
//handle it: must handle it, don't just swallow it.
}
finally {
childDbOps.close();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11834 次 |
最近记录: |