else: w/o except: - why not?

Robin Munn rmunn at pobox.com
Wed Apr 2 10:42:45 EST 2003


Cameron Laird <claird at lairds.com> wrote:
> I want to be clear about the judgment that "a bare except is bad
> practice".  Are you talking about any unqualified except?  Is
>   try:
>       f1()
>   except ZeroDivisionError:
>       f2()
>   except:
>       f3()
> an instance of "a bare except" in the sense that you intend here?

For myself, I'd say yes. Unless f3() is a function specifically written
to handle any and all kinds of exceptions, e.g. by returning an HTML
traceback over CGI instead of printing the traceback to stderr, then the
above code is bad practice.

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

Yes; the above code is *not* bad practice, IMHO, because it allows
exceptions (which presumably are *not* handled by f2()) to propagate
upwards. The problem with bare except is that there are almost always
some exceptions, like SystemExit, which you *want* to propagate upwards.
Catching those without re-raising them is usually a bug.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list