[Tutor] Exception attributes?

Magnus Lyckå magnus at thinkware.se
Sat Jul 10 10:35:50 CEST 2004


At 19:52 2004-07-09 +0000, Jerry McBride wrote:
>It seems that each exception has different attributes. How can I discover
>what attributes are?

In practice you will typically only catch particular
exceptions that you expect to occur in that situation.
If you don't know what kind of exception it is, you
can't be expected to be able to handle it properly.

E.g.

try:
     x = a / b
except ZeroDivisionError:
     x = None

or

try:
     char = aString[pos]
except IndexError:
     char = ''

There are certainly situations where you might want to
do something like...

except (KeyError, NameError, IndexError), e:

...but you very rarely catch exceptions in production code
without knowing what class (or set of classes) they are, and
thus what attributes you are interested in.

I imagine that you might want to catch unexpected exceptions
on a high level in the application so that you can give some
generic error message about program error or an unexpected
condition, log the error and shut down the application in an
ordered way.

You can probably have a look at the cgitb module to see how
that could be handled. Showing a decorated traceback in a log
similar to the way cgitb does it is probably much better than
to show whatever attributes the excption object might have. I
think a plain, simple traceback is better than exception object
attributes in a log.

Besides, you can always show the attributes in any instance
object o through o.__dict__.

You can print the traceback from the last exception through
import traceback; traceback.print_last()



--
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