[Python-Dev] Bare except clauses in PEP 348

Raymond Hettinger raymond.hettinger at verizon.net
Wed Aug 24 03:23:32 CEST 2005

The latest version of PEP 348 still proposes that a bare except clause
will default to Exception instead of BaseException.  Initially, I had
thought that might be a good idea but now think it is doomed and needs
to be removed from the PEP.

A bare except belongs at the end of a try suite, not in the middle.
This is obvious when compared to:

  if a:    ...
  elif b:  ...
  elif c:  ...
  else:    ...     # The bare else goes at the end 
                   # and serves as a catchall


  switch c
  case a:  ...
  case b:  ...
  default: ...     # The bare default goes at the end
                   # and serves as a catchall

In contrast, Brett's 8/9 note revealed that the following would be
allowable and common if the PEP is accepted in its current form:

  try:     ...
  except:  ...     # A bare except in the middle.  WTF?
  except (KeyboardInterrupt, SystemExit): ...

The right way is, of course:

  try:     ...
  except (KeyboardInterrupt, SystemExit): ...
  except:          # Implicit or explicit match to BaseException
                   # that serves as a catchall

For those not needing a terminating exception handler, the rest of the
PEP appropriately allows and encourages a simple and explicit solution
that meets most needs:

  try:               ...
  except Exception:  ...

The core issue is that the most obvious meaning of a bare except is
"catchall", not "catchmost".  When the latter is intended, the simple
and explicit form shown in the last example is the way to go.  If the
former is intended, then either a bare except clause or explicit mention
of BaseException will do nicely.

However, under the PEP proposal, both new and existing code will suffer
from having bare except clauses that look like they catch everything,
are intended to catch everything, but, in fact, do not.  That kind of
optical illusion error must be avoided.  There is no getting around our
mind's propensity to interpret the bare form as defaulting to the top of
the tree rather than the middle as proposed by the PEP.  

Likewise, there is no getting around the mental confusion caused a bare
except clause in the middle of a try-suite rather than at the end.  We
have to avoid code that looks like it does one thing but actually does
something else.


More information about the Python-Dev mailing list