Python and Exceptions containing Unicode messages
Python (2.4 and 2.5 tested) seems to have problems when an exception is thrown that contains non-ASCII text as a message.
In my case I constructed an exception like
>>> try: ... raise Exception(u'Error when printing ü') ... except Exception, e: ... print e ... Traceback (most recent call last): File "", line 4, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 20: ordinal not in range(128)
That's at least what the tutorial advocates [1].
Same with unicode(e)
instead of the print directive.
Using unicode(e, 'utf8')
doesn't do the job:
TypeError: coercing to Unicode: need string or buffer, instance found
A method __unicode__()
doesn't seem to exist [2], and thus I'm only left with:
>>> try: ... raise Exception(u'Error when printing ü'.encode('utf8')) ... except Exception, e: ... print e ... Error when printing ü
UTF-8 is my systems default encoding.
It seems I'm not the first one to stumble upon this behavior [3], I just wonder why an error like this can still exist in 2008. Maybe I should file a bug report.
Update: the bug report