Database exception handling can create more intuitive user experience during accessing persistence database. To avoid exception handling sometimes may increase application crash.
Today we learn about exception handing with room. SQLiteConstraintException can be very common if primary key is getting from user input(Ex: vocabulary database. Here, word is unique key and it can be user input). In this case user should get clear message what is happening instead of application crash while inserting duplicates. And it is only possible if we catch the exception and show proper message to users.
We can handle exceptions easily by the following way:
Java
//DAO
@Insert(onConflict =OnConflictStrategy.ABORT )
void insert(Word word) throws Exception;
//Exception Handling while calling insert function
Thread((Runnable) () -> {
try {
wordDao.insert(word);
} catch (SQLiteException e) {
//handle exception
//show message
}
}).start();
Kotlin
//DAO
@Insert(onConflict =OnConflictStrategy.ABORT )
@Throws(SQLiteException::class)
fun insert(word: Word)
//Exception Handling while calling insert function
Thread {
try {
wordDao.insert(word)
} catch (e: SQLiteException) {
//handle exception
//show message
}
}.start()
Kotlin Coroutines
//DAO
@Insert(onConflict =OnConflictStrategy.ABORT )
@Throws(SQLiteException::class)
suspend fun insert(word: Word)
//Exception Handling while calling insert function
scope.launch {
try {
wordDao.insert(word)
} catch (e: SQLiteException) {
//handle exception
//show message
}
}
Comments