Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how should I handle DB access exceptions?

My question is about good practices of DB exception handling.

Let say I've got an application that stores some data in DB. There are the following layers implemented:

  1. DatabaseAdapter - deals with SQL queries and provides data to the higher layer in form of a model. Adapter contains a methods like:
    • List getAllUsers()
    • void addUser(UserModel user)
  2. UserListActivity - shows the list of all users, allows to add a new user etc. This activity uses DatabaseAdapter to read/write the database.

The question is: shall I handle an exception of database access, for example when adding a new record (assuming that the record should always be added correctly) ? Shall I just try-catch the exception in DatabaseAdapter and add it to log? Or maybe I shouldn't catch it at all?

like image 810
kmalmur Avatar asked Oct 05 '22 18:10

kmalmur


1 Answers

Most of the time, an Exception when querying a database is the result of a "development time" mistake, like a malformed query, or modifying your schema but not incrementing the database version, or something like that. These will be pretty easy to find and fix right on the spot, so your end users won't be effected by these types of mistakes.

However, there are also real possibilities that you may have exceptions in the following cases:

  • You try to access your SQLite database from multiple processes (a recipe for disaster).
  • The user runs out of disk space on their device.
  • You have a malformed query due to not escaping user input properly.
  • There's a bug in your onUpgrade() method or something like that.
  • You are using referential integrity (possible in SQLite 3.6.19 and up) and some table constraint fails.

Really, there's no universal answer for these scenarios. For the end user, showing a simple error is much nicer than having your app force close for example.

My rule of thumb is to avoid corruption of your database at all costs. I would much rather throw a RuntimeException and immediately kill the app rather than having it silently do something wrong. Also, I'd rather show a message saying that an insert could not be completed rather than force closing the app.

like image 142
wsanville Avatar answered Oct 13 '22 11:10

wsanville