python - 在 Python 中使用内置 str() 类型的潜在异常

标签 python string python-3.x exception-handling built-in

在 Python 中使用 intfloat 等内置类型时,通常在输入可能不可靠的情况下使用异常处理:

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() 时是否需要注意任何突出的边缘情况?

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!'

我真的不喜欢使用宽泛的 Exception,因为有像 NameError 这样的情况表明代码有问题,应该引发错误。我已经将 UnicodeError 视为候选对象,但我不确定 str() 是否会导致它(与 foo.encode()foo.decode(),它更容易理解)并且会喜欢什么输入的例子,如果有的话,会触发它。

总结:即使输入不可靠,在没有 try/except block 的情况下使用 str() 通常是否安全?

最佳答案

In summary: Is it generally safe to use str() without a try / except block even with unreliable input?

这取决于我们谈论的是哪种输入。您已将此问题标记为 Python 3,因此您无需担心使用 Python 2 和 Unicode 输入时出现的 UnicodeEncodeErrors,但您收到的对象可以在其 __str__< 中执行几乎所有操作__repr__,引发几乎任何类型的异常。例如,

In [18]: import weakref

In [19]: class Foo(object): pass

In [20]: str(weakref.proxy(Foo()))
---------------------------------------------------------------------------
ReferenceError                            Traceback (most recent call last)
<ipython-input-20-396b2ab40052> in <module>()
----> 1 str(weakref.proxy(Foo()))

ReferenceError: weakly-referenced object no longer exists

关于python - 在 Python 中使用内置 str() 类型的潜在异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38380335/

相关文章:

python - Pyspark:如何处理 python 用户定义函数中的空值

string - 在 Excel 的 VBA 中,当字符串包含 '&' 时如何操作页眉/页脚

python - v4l2 文档的示例代码原样(打开为 'rw' )?

python - 我的程序不会给出成绩

python-3.x - python : How to use speech_recognition or other modules to convert base64 audio string to text?

python 控制台选项卡完成在 Windows 中不起作用

python - Django - 让中间件与 View /模板通信

python - 使用python在redis中进行 key 压缩

java - 如何解析计算器项目中的操作数和运算符?

java - 如何在 Java 中拆分具有多个分隔符的字符串