繁体   English   中英

Python 2 检测到除块之外的异常但未检测到 Python 3

[英]Python 2 detects exception outside except block but not Python 3

在 python 2 中运行时,我发现这段代码在 try 块本身内检测到异常。

import sys
for i in range(3):
    try:
        if sys.exc_info()[1]:
            print("Exception found")
        else:
            print("Exception not found")
        raise Exception("Random exception")
    except Exception as e:
        pass

python 2.7.17 生成的 Output -

Exception not found
Exception found
Exception found

在 python 3 上运行时,未检测到异常。
python 3.7.7 生成的 Output -

Exception not found
Exception not found
Exception not found

为什么 python 2 会这样? python 2 中是否有任何解决方法来避免这种行为?
使用 gunicorn 运行时,错误的异常检测会导致我的应用程序日志丢失。

关于“处理异常”的含义,在此上下文中 Python 2 和 Python 3 之间存在差异。 最好通过相关文档条目的差异( Py2Py3 )进行可视化:

文档差异

因此,虽然在 Python 3 中,此定义仅包括当前正在处理的异常,但在 Python 2 中也包括最近处理的异常

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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