In your last few examples, you use a generic except statement to tidy up loose ends (such as database transactions and busy cursors). Sometimes, the finally keyword is more suited to this task. The finally keyword makes sure that a section of code is always executed, even if the function ends via an exception or a return statement.
I'll attempt some code in demonstration, using a rewrite of your final example, though I'm not sure how successful it will turn out due to the formatting on these comments:
from threading import Lock
DATA_LOCK = Lock()
try:
DATA_LOCK.acquire()
.. perform operations on global data ...
finally:
# always unlock
DATA_LOCK.release()
try - finally
In your last few examples, you use a generic except statement to tidy up loose ends (such as database transactions and busy cursors). Sometimes, the finally keyword is more suited to this task. The finally keyword makes sure that a section of code is always executed, even if the function ends via an exception or a return statement.
I'll attempt some code in demonstration, using a rewrite of your final example, though I'm not sure how successful it will turn out due to the formatting on these comments:
from threading import LockDATA_LOCK = Lock()
try:
DATA_LOCK.acquire()
.. perform operations on global data ...
finally:
# always unlock
DATA_LOCK.release()