Recommended exception method for modules?

Toby Dickenson mbel44 at dial.pipex.net
Thu Oct 5 12:41:54 EDT 2000


ge at nowhere.none (Grant Edwards) wrote:

>In article <rf1D5.214$Y32.14283 at newsb.telia.net>, Fredrik Lundh wrote:
>
>>For simple cases, reuse an existing exception (if reasonable),
>>or use a single exception class, either inherited from
>>Exception or from a suitable standard exception class
>>(alternative 2).
>
>I decide that my baud rate example is going to be a ValueError.
>My tests and  section 6.8 of the language reference seem to
>show that the following two statements are identical
>
>   raise ValueError, 'invalid baud rate: '+str(rate)
>   raise ValueError('invalid baud rate: '+str(rate))
>
>Is there any reason to use one form over the other?  
>
>The former seems to be the traditional usage (presumably
>because it worked when ValueError was a string), while in the
>latter it's a bit more obvious that a class is being
>instantiated.

Youve just hit on one of my current peeves..... Its increasingly
common (thanks to unicode objects) for a the str() function itself to
raise an exception. Using str() inside error reporting code is a whole
new world of pain.

It might not be valid to pass a Unicode object to this function, but
the whole point of this exception is to report such invalid values!

I suggest:

raise ValueError('invalid baud rate', rate)

or 

raise ValueError('invalid baud rate: '+repr(rate))



Toby Dickenson
tdickenson at geminidataloggers.com



More information about the Python-list mailing list