Android SQLite FAQ: I’m trying to catch an exception when my SQLiteOpenHelper/SQLiteDatabase insert
method fails (typically because of a unique/duplicate constraint); why can’t I catch the exception?
Solution: The SQLiteOpenHelper insert
method (SQLiteDatabase, actually) doesn’t throw an exception. The insert
method returns the ID of the newly inserted row if it succeeds, or -1
if it fails. If you want an exception when the insert
method fails, use the insertOrThrow
method instead, as shown in this Java code:
/** * @throws java.sql.SQLException if the insert fails (typically because of a * "duplicate/unique" constraint. */ public long insert(String quote) { ContentValues cv = new ContentValues(); cv.put(COL_QUOTES_QUOTE, quote); return getWritableDatabase().insertOrThrow(TABLE_QUOTES, null, cv); }
The signature for insertOrThrow
is the same as the insert
method, so this is a simple change, assuming you want an exception. As my documentation shows, the insertOrThrow
method throws a standard Java SQLException
if the SQL INSERT fails.
For more information, see the SQLiteDatabase javadoc.