Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLiteConstraintException not caught

What is the problem with this code? It doesn't catch the exception thrown by insertChild() method.

childDbOps.open();
try {
    childDbOps.insertChild(child);
} catch (SQLiteException exception) {
    Log.i("error la inserare child", "on the next line");
    exception.printStackTrace();
} finally {
    childDbOps.close();
}

The error is:

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) 

It is android sqlite. The line is when the insert method is called.

like image 901
bogdan Avatar asked Aug 06 '10 06:08

bogdan


2 Answers

The SQLiteDatabase.insert() method is used in the cases where you want to handle database writes without unwinding the stack if a write fails. If you want to catch exceptions when inserting into the database, use the SQLite.insertOrThrow() method. It will throw an exception which you can then catch and handle.

like image 149
Stephan Leroux Avatar answered Nov 13 '22 09:11

Stephan Leroux


You're catching only exceptions of type SQLiteException. If the insertChild method throws any other exception, it won't be caught.

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();
}
like image 3
Amarghosh Avatar answered Nov 13 '22 08:11

Amarghosh