此代码有什么问题?它不会捕获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();
}
错误是:
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)
这是android sqlite。该行是在调用insert方法时。
答案 0 :(得分:39)
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)
答案 1 :(得分:3)
您只捕获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();
}
答案 2 :(得分:0)
@bogdan还有其他地方你正在调用insertChild(child);除了这个地方。你是否在try块中添加了一个跟踪来知道它是否来到这个块并打印如下所示的轨迹。
请告诉我。尝试{Log.i(“来了 这里“);
childDbOps.insertChild(孩子); }