Richard Jones' Log: In praise of try...finally

Mon, 10 Nov 2003

In my old "python anti-pitfalls" entry, I neglected to mention try...finally (though I did mention the "ubiquitous, unencumbering exception system"). According to Python's Language Reference:

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()
    # do some work with the db handle

the 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...

Comment by simon on Sat, 15 Nov 2003

The problem with try-finally, as is unusally the case with exception handling systems, is that, if an exception is thrown in the finally clause and not caught, the earlier exception gets lost. This is hugely irritating.