else: w/o except: - why not?

Michael Chermside mcherm at mcherm.com
Tue Apr 1 10:33:57 EST 2003


Tim Peters writes: 
> ...a bare except is bad practice...

Cameron Laird writes:
> 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?
> And, for you, does
>   try:
>       f1()
>   except:
>       f2()
>       raise
> become *not* bad practice?

I can't speak for Tim, but my OWN opinion is precisely in alignment
with what you have written.

I think that a "bare except" is useful in only two ways. The first
is like a "finally" clause that's skipped if everything works. In
other words, the following bits of code is (almost[1]) equivalent to 
your second example:

    everythingWorked = False
    try:
        f1()
        everythingWorked = True
    finally:
        if not everythingWorked:
            f2()

This doesn't come up much, but it's occasionally useful, and your
version (using bare except with a raise) is a little prettier.

The other situation is running "untrusted plug-in" code of some 
sort. Something like this:

    try:
        randomCodeSomebodyUploaded()
    except:
        logProblem()

But really, that hardly EVER comes up. I wish that guido had made
it harder to spell "bare except" because these situations seem so
unusual. The next best solution is to just avoid it unless you're
SURE you need it.

-- Michael Chermside

        







More information about the Python-list mailing list