python - Python 2 和 3 中捕获的异常实例的范围

标签 python python-2.7 python-3.x exception scope

<分区>

由于在 Python 中变量可以在它们的循环和 try-except block 之外访问,我天真地认为下面的代码片段可以正常工作,因为 e 将可访问:

try:
    int('s')
except ValueError as e:
    pass
print(e)

在 Python 2(2.7 测试)中,它确实按我预期的那样工作,输出是:

invalid literal for int() with base 10: 's'

然而,在 Python 3 中,令我惊讶的是输出是:

NameError: name 'e' is not defined

这是为什么?

最佳答案

后来我找到了一个答案 PEP 3110解释在 Python 3 中,捕获的名称在 except 套件的末尾被删除,以实现更有效的垃圾收集。如果您希望避免这种情况的发生,还有推荐的语法:

Situations where it is necessary to keep an exception instance around past the end of the except suite can be easily translated like so

try:
    ...
except E as N:
    ...
...

becomes

try:
    ...
except E as N:
    n = N
    ...
…

This way, when N is deleted at the end of the block, n will persist and can be used as normal.

关于python - Python 2 和 3 中捕获的异常实例的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44258903/

相关文章:

python - 模块化代码 python 时未知的库

Python 配置解析器

python-3.x - 使用 Python 截断并重新编号与特定 id/组对应的列

python - 如何使用 Python kusto SDK 在 Kusto 中查看详细数据

python - django admin中内联模型的分页器

python - 一键对具有多个键的字典求和的最有效方法是什么?

python - 执行具有 "from __future__ import ..."的 AquaMacs 缓冲区

python - 将递归函数变成迭代函数

python - 我如何从值是列表的字典中创建字典列表?

java - 新闻的代码拆分/格式 - 需要权威提及