exception arg

Justin Sheehy dworkin at ccs.neu.edu
Tue Jan 4 13:05:58 EST 2000


mn at altern.org (Mirko Nasato) writes:

> >>> 1/0
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> ZeroDivisionError: integer division or modulo
> >>> try:
> ...     1/0
> ... except ZeroDivisionError, arg:
> ...     if arg == "integer division or modulo":
> ...             print "This is what I expect."
> ...     else:
> ...             print 'Unexpected. "arg" is "%s".' % arg
> ... 
> Unexpected. "arg" is "integer division or modulo".
> >>>

In older versions of Python, exceptions were string objects.  As of
Python1.5, they are generally class objects.

Perhaps this will make things a little clearer:

>>> try:
...   1/0
... except ZeroDivisionError, arg:
...   if str(arg) == "integer division or modulo":
...     print "This is what I expect."
... 
This is what I expect.
>>> try:
...   1/0
... except ZeroDivisionError, arg:
...   x = arg
... 
>>> x
<exceptions.ZeroDivisionError instance at 80dff60>
>>> str(x)
'integer division or modulo'

>From the standard documentation:

Exception 
       The root class for exceptions. All built-in exceptions are
       derived from this class. All user-defined exceptions should also
       be derived from this class, but this is not (yet) enforced. The 
       str() function, when applied to an instance of this class (or
       most derived classes) returns the string value of the argument
       or arguments, or an empty string if no arguments were
       given to the constructor. When used as a sequence, this
       accesses the arguments given to the constructor (handy for
       backward compatibility with old code). The arguments are also
       available on the instance's args attribute, as a tuple. 


-Justin

 




More information about the Python-list mailing list