try except bug
Chad Netzer
cnetzer at mail.arc.nasa.gov
Fri Jan 10 00:23:33 EST 2003
On Thursday 09 January 2003 20:31, Gang Seong wrote:
> I think there is a bug in try-except clause.
nope
> 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:
http://www.python.org/doc/current/ref/exceptions.html
"""
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.
http://www.python.org/doc/current/lib/module-exceptions.html
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
try:
f()
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 - http://www.baypiggies.net/
Chad Netzer
cnetzer at mail.arc.nasa.gov
More information about the Python-list
mailing list