else: w/o except: - why not?

Tim Peters tim.one at comcast.net
Tue Apr 1 22:53:57 EST 2003


[Cameron Laird]
> I'm leaving aside Mr. Hand's goals; I'm still unsure about them.
>
> I want to be clear about the judgment that "a bare except is bad
> practice".  Are you talking about any unqualified except?

It's the semantics:  *most* bare excepts swallow all exceptions blindly, and
that's almost never what the author intended.  When it is, it should be
commented.  A syntactic bare except may have unobjectionable semantics, as
in your second example below:

> Is
>   try:
>       f1()
>   except ZeroDivisionError:
>       f2()
>   except:
>       f3()
> an instance of "a bare except" in the sense that you intend here?

Semantically, yes.  It's almost certain that the author did not intend that
(among others):

1. The failure to *find* the name f1 would call f3(), via "f1" raising
   NameError or UnboundLocalError.  The bare except here is a fine way to
   change a typo into mysterious behavior.

2. Trying to terminate the program via Ctrl-C would lead to Ctrl-C getting
   ignored, calling f3() instead, due to the bare except swallowing the
   KeyboardInterrupt exception.

3. Trying to terminate the program via sys.exit() would get ignored, due to
   the bare except swallowing the SystemExit exception.

> And, for you, does
>   try:
>       f1()
>   except:
>       f2()
>       raise
> become *not* bad practice?

Since it doesn't swallow any exceptions, this example is immune to the
surprises of the first example.  It's still questionable whether the author
*really* intended to catch every possible exception coming out of f1(),
though, and I'd be happier with a comment about why this code is appropriate
in context.  For example, perhaps f2() logs the pending exception state.

bad-practice-gets-worse-with-practice-ly y'rs  - tim






More information about the Python-list mailing list