[Zope3-dev] Please, no bare 'except:' clauses!
Guido van Rossum
guido@python.org
Mon, 11 Nov 2002 09:49:22 -0500
> 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
> - In a framework,
What's a framework? "Framework" is one of those words that mean
whatever you wish it to mean. :-)
> where the outermost driver needs to prevent the
> exception from percolating out of the framework, or the framework
> wants to log the exception and move on. E.g.
>
> logger = a_log_file()
> while work_to_do_in_framework():
> try:
> process_one_thing()
> except:
> traceback.print_exc(file=logger)
This feels similar to the command line processor in e.g. IDLE.
The common characteristic seems to be that these take external
descriptions of some work to be done, and they should report success
or failure, plus details like output or traceback. RPC servers
typically also do this: any exceptions raised by an incoming call
should be caught and propagated to the client, rather than killing the
RPC server.
> I'm sure others can come up with more useful patterns and
> antipatterns. Perhaps PEP 8 would be a good place to document
> recommendations.
+1 as long as I don't have to write it (I'll review it :-).
--Guido van Rossum (home page: http://www.python.org/~guido/)