[Tutor] except AttributeError, TypeError:

Magnus Lyckå magnus at thinkware.se
Sun May 2 14:27:55 EDT 2004


At 17:24 2004-05-01 -0700, Danny Yoo wrote:
>    try:
>         do_much_stuff()
>     except (AttributeError, TypeError):
>         do_it()

Note that you *must* *not* forget the parenthesis here.
It's perfectly legal to write...

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

...but it won't do what you expect!

Remember that you can write:

try:
     do_much_stuff()
except AttributeError, my_attribute_error_object:
     print my_attribute_error_object

In other words, the except statement takes two parameters,
first an exception class (or a tuple of exceptions classes),
and secondly the variable you want to reference your
exception object.

Both arguments are optional, but since they are positional,
you can't write the second argument without writing the
first, i.e. you must write a class name (at least) to be
able to get the exception object to a variable.

This isn't a problem though, since you don't need to write
the concrete class that the exception object belongs to.
Any super class is also fine, so the base class for all
exception will catch all exceptions. I.e.

except Exception e:

will catch all exceptions, and you will get a reference
to the exception object through the variable 'e'.


--
Magnus Lycka (It's really Lyckå), magnus at thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 




More information about the Tutor mailing list