try except bug

Erik Max Francis max at alcyone.com
Fri Jan 10 06:28:55 CET 2003


"ÀÌ°­¼º" wrote:

> I think there is a bug in try-except clause.
> If you use 'raise' with a string type exception and class instance,
> that's
> OK. But, when you 'raise' with a class type exception and class
> instance, it
> works in a strange way. Look at the following code.

That's because you're not quite doing it right.  Note that raising
anything other than classes that derive from Exception is deprecated.

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

Make sure MessageClass derives from Exception:

	class MessageClass(Exception): ...

> def f():
>     raise Exception, MessageClass()

The syntax here you want is

	raise MessageClass()

What you're doing is legal, too, but is the equivalent of

	raise Exception(MessageClass())

so when you catch it later, you're catching an exception of type
Exception, not your MessageClass that you probably meant.  You can
access the MessageClass instance from the a.args tuple, but from the
look of your exception handling code that isn't what you meant.

> try:
>     f()
> except Exception, a:
>     print a, type(a)
>     print a.duration   # This one doesn't work.

And this is the syntax you want here, not except 'Exception'.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ The basis of optimism is sheer terror.
\__/ Oscar Wilde
    CSBuddy / http://www.alcyone.com/pyos/csbuddy/
 A Counter-Strike server log file monitor in Python.




More information about the Python-list mailing list