11
votes

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.

3
Have you tried to just catch any exception using catch (Exception e){} ? It might give you a hint. - Benny Skogberg
where does the exception indicate it was thrown from? make sure all your code is in a big generic try block & see what happens. which API is this - android sqlite? - Sam Brightman
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) yes, it is android sqlite. the line is when the insert method is called - bogdan

3 Answers

44
votes

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.

3
votes

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();
}
0
votes

@bogdan is there any other place u are calling insertChild(child); other than this place. did you put a trace in try block to know whether it comes to this block and print the trace like below.

try { Log.i("comes here");
childDbOps.insertChild(child); }

let me know.