在Python中使用内置的str()类型的潜在异常 [英] Potential Exceptions using builtin str() type in Python
问题描述
在Python中使用内置类型,如 int
和 float
时,通常使用异常处理输入可能不可靠的情况:
When working with built-in types like int
and float
in Python, it's common to employ exception handling in cases where input might be unreliable:
def friendly_int_convert(val):
"Convert value to int or return 37 & print an alert if conversion fails"
try:
return int(val)
except ValueError:
print('Sorry, that value doesn\'t work... I chose 37 for you!')
return 37
有没有突出的边缘案例要注意使用 str()
?
Are there any prominent edge-cases to be aware of when using str()
?
def friendly_str_convert(val):
"Convert value to str or return 'yo!' & print an alert if conversion fails"
try:
return str(val)
except Exception: # Some specific Exception here
print('Sorry, that value doesn\'t work... I chose \'yo!\' for you!')
return 'yo!'
我真的不喜欢使用广泛的异常
因为有些情况,例如 NameError
表示代码有问题,应该引发错误。我认为 UnicodeError
作为候选人,但我不知道 str()
是否导致(vs. foo.encode()
和 foo.decode()
更容易理解),并且会喜欢什么输入的例子(如果有的话)会触发它。
I really don't like using a broad Exception
since there are cases like NameError
that signify a problem with the code and should raise an error. I've considered UnicodeError
as a candidate but I'm not sure whether str()
causes it (vs. foo.encode()
and foo.decode()
where it's easier to understand) and would love an example of what input, if any, would trigger it.
总之:使用 str()
尝试
/ 除了
阻止即使有不可靠的输入?
In summary: Is it generally safe to use str()
without a try
/ except
block even with unreliable input?
推荐答案
在这方面, str
和 int
有很大的区别。 int
可以提高 TypeError
和 ValueError
。
There's a huge difference between str
and int
in this regard. int
can definitely raise TypeError
and ValueError
.
就我而言,唯一的例外是 str
可以为普通对象引发 UnicodeEncodeError
:
As far as I can think, the only exception that str
can raise for normal objects is UnicodeEncodeError
:
>>> s = u"a\xac\u1234\u20ac\U00008000"
>>> str(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4: ordinal not in range(128)
这只会发生在python2.x上。
And that only happens on python2.x.
当然,我可以很容易地使一个失败的类失败,几乎有任何异常可以想象: / p>
Of course, I can easily make a class that fails with just about any exception imaginable:
>>> class MyError(Exception):
... pass
...
>>> class Foo(object):
... def __str__(self):
... raise MyError
...
>>> f = Foo()
>>> str(f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __str__
__main__.MyError
在大多数情况下,我会质疑在这一点上处理所有异常 的一些隐含假设。通常情况下,最好只处理您知道如何处理的异常。在这种情况下,由于用户将垃圾放入函数而发生的异常异常应该在垃圾进入的级别处理,而不在函数本身内。捕捉错误并返回一些可能是废话的值不会对调试问题等有帮助。
For the most part, I would question some of the implicit assumptions that all exceptions need to be handled at this point. Generally, it's best to only handle exceptions that you know how to handle. In this case, exotic exceptions that happen because the user put junk into the function should probably be handled at the level where the junk is going in -- not within the function itself. Catching the error and returning some value which is likely nonsense isn't going to be super helpful for debugging issues, etc.
这篇关于在Python中使用内置的str()类型的潜在异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!