[Tutor] except AttributeError, TypeError:

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat May 1 20:24:08 EDT 2004



On Sun, 2 May 2004, Thorsten Kampe wrote:

> What is the best way to except two errors, when the except handling in
> both cases is the same?


Hi Thorsten,


Ah!  There's an slightly cleaner way to do this.  Let's say that we have
this:

###
def do_it():
    try:
        do_much_stuff()
    except AttributeError:
        do_it()
    except TypeError:
        do_it()
###


Here's another way to write the same thing:

###
def do_it():
    try:
        do_much_stuff()
    except (AttributeError, TypeError):
        do_it()
###

We are allowed to pass a tuple of exceptions that we want to handle
uniformly.  The Official Python Tutorial covers this usage here:

http://www.python.org/doc/tut/node10.html#SECTION0010300000000000000000

and it shows another way to do a kind of 'wildcarding' except clause that
captures everything.


If you have more questions, please feel free to ask.  Good luck!




More information about the Tutor mailing list