try except bug

Chad Netzer cnetzer at
Fri Jan 10 06:23:33 CET 2003

On Thursday 09 January 2003 20:31, Gang Seong wrote:
> I think there is a bug in try-except clause.


> Look at the following code.

> class MessageClass:
>     def __init__(self):
>         self.message = 'message'
>         self.duration = 10
> def f():
>     raise Exception, MessageClass()

In section 4.2 of the manual:

When an exception is raised, an object (maybe None) is passed as the 
exception's value; this object does not affect the selection of an 
exception handler, but is passed to the selected exception handler as 
additional information. For class exceptions, this object must be an 
instance of the exception class being raised.

See also, section 2.3 in the python library reference manual.

Basically, your object gets passed along to the args attribute of the 
generated value.  It is a side effect that your print statements 
printed the right types for the objects.  You would probably be better 
served to make your own subclass of Exception and use it to pass the 
values you want around.

The code below prints the expected '10', by grabbing the MessageClass 
object that you made from the args of the value passed to the exception.

It can be confusing, I agree.

class MessageClass:
    def __init__(self):
        self.message = 'message'
        self.duration = 10

def f():
    m = MessageClass()
    print id( m )
    raise Exception, m

except (Exception,), a:
    print a, type(a), id( a )
    print a.args[0], type(a.args[0]), id( a.args[0] )
    print a.args[0].duration

Bay Area Python Interest Group -

Chad Netzer
cnetzer at

More information about the Python-list mailing list