[Tutor] Class as Exception

Jeff Shannon jeff@ccvcorp.com
Mon Feb 10 14:49:10 2003


Bob Gailer wrote:

> A couple of times I got the following to work. Now I just get an 
> exception.
>
> >>> class n(str):pass
> >>> raise n, 'tst'
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> TypeError: exceptions must be strings, classes, or instances, not type
>
> Why would the same code work, then fail?


Did you derive your exception class from str the times that it worked? 
 By doing so, you're making your class into a new-style object (i.e., a 
type) instead of an old-style (instance) object.  That's what the 
interpreter is complaining about.

As others have said, though, if you want to use a class as an exception, 
you really ought to be deriving it from Exception (or some other 
subclass of Exception), not from something like str.  

Jeff Shannon
Technician/Programmer
Credit International