[Zope3-dev] Please, no bare 'except:' clauses!

Guido van Rossum guido@python.org
Tue, 12 Nov 2002 07:28:12 -0500


[Barry]
> >>- To do additional processing whenever an exception in a sub-call
> >>  occurs.  In this case you always re-raise the original exception
> >>  after doing the processing.  E.g.
> >>
> >>  txn = a_bdb_transaction()
> >>  try:
> >>      val = do_some_work()
> >>  except:
> >>      txn.abort()
> >>      raise
> >>  else:
> >>      txn.commit()
> >>      return val

[Guido]
> > I would prefer to write that as follows:
> > 
> >   txn = a_bdb_transaction()
> >   ok = 0
> >   try:
> >     val = do_some_work()
> >     ok = 1
> >   finally:
> >     if ok:
> >       txn.commit()
> >     else:
> >       txn.abort()
> >   return val

[Jim]
> Why is that? The former looks cleaner to me.
> 
> At first glance, the logic looked wrong to me.  I had
> to think a bit to realize that it propigates the exception that
> is raised and that it only returns a value if there is no exception.

On second though, I'm not so sure.  The problem I had with the first
one is that the essential 'lone raise' was somewhat hidden; but you're
right that the flow control is no simpler in the try/finally version.

--Guido van Rossum (home page: http://www.python.org/~guido/)