Unicode strings as arguments to exceptions
Roy Smith
roy at panix.com
Thu Jan 16 09:32:17 EST 2014
In article <52d7e9a0$0$29999$c3e8da3$5496439d at news.astraweb.com>,
Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> On Thu, 16 Jan 2014 13:34:08 +0100, Ernest Adrogué wrote:
>
> > Hi,
> >
> > There seems to be some inconsistency in the way exceptions handle
> > Unicode strings.
>
> Yes. I believe the problem lies in the __str__ method. For example,
> KeyError manages to handle Unicode, although in an ugly way:
>
> py> str(KeyError(u'ä'))
> "u'\\xe4'"
>
> Hence:
>
> py> raise KeyError(u'ä')
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> KeyError: u'\xe4'
>
>
> While ValueError assumes ASCII and fails:
>
> py> str(ValueError(u'ä'))
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in
> position 0: ordinal not in range(128)
>
> When displaying the traceback, the error is suppressed, hence:
>
> py> raise ValueError(u'ä')
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> ValueError
>
>
> I believe this might be accepted as a bug report on ValueError.
If you try to construct an instance of ValueError with an argument it
can't handle, the obvious thing for it to do is raise ValueError :-)
More information about the Python-list
mailing list