[Zope3-dev] Please, no bare 'except:' clauses!
Jim Fulton
jim@zope.com
Mon, 11 Nov 2002 18:05:18 -0500
Guido van Rossum wrote:
>>Maybe we should start documenting places where bare except is
>>acceptable and where it isn't. Not as an exclusive list, but as a
>>helpful guide for programmers to decide when to use it and when not
>>to use it. Here's a start of some places where I think bare except
>>is okay:
>>
>>- 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
>>
>
> 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
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.
Jim
--
Jim Fulton mailto:jim@zope.com Python Powered!
CTO (888) 344-4332 http://www.python.org
Zope Corporation http://www.zope.com http://www.zope.org