I’m developing an Android 3.1 and above application, but this question is not specific for a particular environment.
I have three layers: activities (presentation), models (objects that represents database tables), and data (classes to access SQLite database).
All of my database methods are like this one:
public void insertUserAnswers(ArrayList<UserAnswer> answers)
{
try
{
if ((db == null) || (!db.isOpen()))
this.open();
}
catch (Exception e) {
e.printStackTrace();
}
finally
{
this.close();
}
}
As you can see I catch every exception and I don’t notify anyone about it because (and this is my problem) I don’t know how to do it.
How can I notify that it was an error on a sql command? Is there any pattern to do that?
I think I can return a value to indicate that or without caching exceptions.
Firstly, do not catch all Exceptions like that, it will become difficult to know what went wrong and to notify the user of exactly what is wrong. Instead do something like this:
You see that we capture
Exceptionright at the end, sort of a capture-all type thing to make sure that we haven’t missed anything.In terms of your model, the way I do it is to make sure that all the Data Layer objects throw their exceptions up to the presentation layer (activities) so that the activity can deal with it. At the presentation layer you can choose how to present the error to the user: usually in a nice, informative error message. This might not always be the case though. If for instance you are populating your model and hit a null pointer because there are no returns from the DB then catch the problem at the Data layer and just don’t populate the model. Then when your presentation layer goes to present the model there won’t be anything there and that is the point at which your presentation layer can decide how to convey that to the user.
In summary: don’t catch the exceptions in the data layer unless really necessary.