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

Barry A. Warsaw barry@zope.com
Mon, 11 Nov 2002 09:41:06 -0500


>>>>> "GvR" == Guido van Rossum <guido@python.org> writes:

    GvR> Hear, hear.  Bare except is one of the most over-used
    GvR> features of Python.  Let's ban it except for very carefully
    GvR> thought-out and documented situations.

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

- In a framework, 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)

I'm sure others can come up with more useful patterns and
antipatterns.  Perhaps PEP 8 would be a good place to document
recommendations.

-Barry