[Python-Dev] Bare except clauses in PEP 348

Shane Hathaway shane at hathawaymix.org
Wed Aug 24 18:17:20 CEST 2005

Barry Warsaw wrote:
> I agree about bare except, but there is a very valid use case for an
> except clause that catches every possible exception.  We need to make
> sure we don't overlook this use case.  As an example, say I'm building a
> transaction-aware system, I'm going to want to write code like this:
> txn = new_transaction()
> try:
>     txn.begin()
>     rtn = do_work()
> except AllPossibleExceptions:
>     txn.abort()
>     raise
> else:
>     txn.commit()
>     return rtn
> I'm fine with not spelling that except statement as "except:" but I
> don't want there to be any exceptions that can sneak past that middle
> suite, including non-errors like SystemExit or KeyboardInterrupt.
> I can't remember ever writing a bare except with a suite that didn't
> contain (end in?) a bare raise.  Maybe we can allow bare except, but
> constrain things so that the only way out of its suite is via a bare
> raise.

I also use this idiom quite frequently, but I wonder if a finally clause 
would be a better way to write it:

txn = new_transaction()
     rtn = do_work()
     if exception_occurred():
         return rtn

Since this doesn't use try/except/else, it's not affected by changes to 
the meaning of except clauses.  However, it forces more indentation and 
expects a new builtin, and the name "exception_occurred" is probably too 
long for a builtin.

Now for a weird idea.

txn = new_transaction()
     rtn = do_work()
finally except:
finally else:
     return rtn

This is what I would call qualified finally clauses.  The interpreter 
chooses exactly one of the finally clauses.  If a "finally except" 
clause is chosen, the exception is re-raised before execution continues. 
  Most code that currently uses bare raise inside bare except could just 
prefix the "except" and "else" keywords with "finally".


More information about the Python-Dev mailing list