Reputation: 828
When I am executing a simple query (I am using tornado.database module) I handle exceptions like this:
try:
self.application.db.execute('DELETE FROM table_one WHERE a = 1')
except Exception, e:
logging.warning('DB exception: %s' % e)
self.set_status(500)
return
If I want to do a transaction though, it would be smart to rollback it in case of exception:
try:
self.application.db.execute('START TRANSACTION')
self.application.db.execute('DELETE FROM table_one WHERE a = 1')
self.application.db.execute('DELETE FROM table_two WHERE b = 2')
self.application.db.execute('COMMIT')
except Exception, e:
logging.warning('DB exception: %s' % e)
self.set_status(500)
self.application.db.execute('ROLLBACK')
return
But what if rollback will cause an exception too (e.g. if connection fails)? Do I need to put a nested try-except block inside of the except block?
Upvotes: 1
Views: 12219
Reputation: 23876
better to check recommendations from here
according to PEP, main points I would like to highlight here:
Upvotes: 0
Reputation: 1195
Placing a nested try ... except block in except block is a solution. But I would go for using finally:
try:
...
except ... :
finally:
# cleanup (close the connection, etc...)
I mean if the rollback failed, there is pretty much nothing else to do then log the exception and cleanup, right?
Upvotes: 2