Added additional error handling so that the database is closed properly