Richard Jones' Log: In praise of try...finally
The try...finally form specifies a `cleanup' handler. The try clause is executed. When no exception occurs, the finally clause is executed. When an exception occurs in the try clause, the exception is temporarily saved, the finally clause is executed, and then the saved exception is re-raised.
Put simply, it means that in the following code:
db = open_database() try: # do some work with the db handle finally: db.close()
db.close() part always gets run, regardless of whether there was some exception while using the db handle. This is crucial for databases such as Berkeley DB (which has a habit of getting corrupted if not treated with the utmost respect), or in situations where the db may have references that need cleaning up such as mysql.
Now, I just need to figure how to install
finally handlers in my life...