Exception Messages

Terry Reedy tjreedy at udel.edu
Mon Oct 15 15:15:30 EDT 2012


On 10/15/2012 12:22 PM, John Gordon wrote:
> In <mailman.2217.1350317845.27098.python-list at python.org> MRAB <python at mrabarnett.plus.com> writes:
>
>>> Why wasn't the message printed out?
>>
>> You didn't add a __str__ method:
>
>> class PvCamError(Exception):
>>       def __init__(self, msg):
>>           self.msg = msg
>>       def __str__(self):
>>           return self.msg
>
> Wouldn't PvCamError inherit __str__() from Exception?

Exception instances get a .args attibute set to the arguments of the 
class call and printed in the .__str__ message.

 >>> dir(Exception())
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', 
'__dir__', '__doc__', '__eq__', '__format__', '__ge__', 
'__getattribute__', '__gt__', '__hash__', '__init__', '__le__', 
'__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', 
'__subclasshook__', '__suppress_context__', '__traceback__', 'args', 
'with_traceback']
 >>> Exception('abc', 1)
Exception('abc', 1)

So class MyError(Exception) will get that basic default behavior. For 
fancier printing, one needs a fancier .__str__ method ;-).

-- 
Terry Jan Reedy




More information about the Python-list mailing list