SQLiteConstraintException未被捕获

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)

  • 这就是答案。实际报告的不是缺少捕获引发的错误。错误实际上没有被抛出。但是,它被打印到原木上。但是,使用insertOrThrow()会引发异常-然后可以将其捕获。这对于解决已知问题(例如OP约束异常)很有用。 (2认同)

Ama*_*osh 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();
}
Run Code Online (Sandbox Code Playgroud)