简体   繁体   中英

Can str raise exception?

Is there any chance that str can raise exception for non-callable argument ? Apart of custom classes that could override __repr__ for some reason ?

I have some argument on enter of function and if it's not str I am converting it to it. I'm curious if I have to handle exceptions, and if I have to, which ones ? Handling Exception is not good practice but it seems like it's the only way.

Edit: By no-callable I mean that the argument is not executed inside str, like str(get_something_to_convert()) . In this example I should handle exceptions in inner function.

Any class could override __str__ for any reason because str calls __str__ , not __repr__ , if both are defined. IMHO that is, by itself, enough reason to be prepared to get exceptions.

But a common pitfall for non-English users is Unicode strings with Python 2.x. Just look at the following code:

>>> a = u'\xe9\xe8'
>>> print a
éè
>>> str(a)

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    str(a)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1:
 ordinal not in range(128)

So a simple Unicode string containing non-ASCII characters will throw an exception when you call str on it.

It is up to you whether you prefer to handle the exception, or document that the function only accepts arguments that can be directly converted to string with str .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM