[Tutor] global exception handling?

Evert Rol evert.rol at gmail.com
Mon Aug 2 23:08:45 CEST 2010


> A week or two back I asked this list about how to deal with SQLite database errors like 'database is locked'.  Since then I figured out one way to reproduce that error (*see p.s. below if anyone is interested).  I can also then catch the error with a try/except block and prevent it from causing problems.
> 
> But, the issue is, I have many places where I write to the database and would have to embed each of these in a try/except block.  I can do that, but wondered if there is a "global" way to catch this 'database is locked' error?  I found someone asking this sort of question online but it doesn't appear to be answered:
> http://bytes.com/topic/python/answers/799486-how-do-i-prevent-exceptions-stopping-execution-global-exception-handler

I'm not sure why you would like to do that: your code assumes the database interaction works fine, and based on that just continues it's normal flow. If the database is locked, you'll need to do something to prevent your code crashing further down, which is what you put in the except OperationalError: block. I would assume that the error handling depends on where you are in the code.
If you can always perform the same type of error handling, just create a convenience function (possibly with the SQL statement as argument) that calls the database and returns the results, and put the database call inside the try: except: clause. Then you need to do this only once.

A global way to catch the database-locked exception is just to put the try: except OperationalError: around your complete code. Exceptions propagate all the way to the function where your program started, and if you catch it there, you will catch every OperationalError exception from anywhere in the code. Of course, your program then always exits anyway, because you can't return to the point where the the exception was thrown (or maybe you can, but not that I'm aware of. I wouldn't recommend it though).


> Thanks,
> Che
> 
> p.s. *I use the nice program SQLite Database Browser and if I edit a field in the database my Python app is accessing, click "Apply changes", but I do *not* save the changes (that is, I do not click the disk icon), when I go to write to that database from my Python app, I get a 'database is locked' error.

Sounds like somewhat odd behaviour to me: "apply changes" for me means "apply & commit", ie, it includes the save operation. Might just be me.
I guess "Apply changes" opens the database connection, but then "save" performs the actual commit to the database, and in the meantime the database is locked.



More information about the Tutor mailing list