[英]Python 2 detects exception outside except block but not Python 3
I found this piece of code detecting exception within the try block itself when run in python 2.在 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
Output generated by python 2.7.17 - python 2.7.17 生成的 Output -
Exception not found
Exception found
Exception found
When run on python 3, the exception is not detected.在 python 3 上运行时,未检测到异常。
Output generated by python 3.7.7 - python 3.7.7 生成的 Output -
Exception not found
Exception not found
Exception not found
Why does python 2 behave this way?为什么 python 2 会这样? Is there any workaround in python 2 to avoid this behavior? python 2 中是否有任何解决方法来避免这种行为?
Wrong exception detection is throwing off my application's logging when run using gunicorn.使用 gunicorn 运行时,错误的异常检测会导致我的应用程序日志丢失。
Regarding the meaning of "handling an exception" there is a difference between Python 2 and Python 3 in this context.关于“处理异常”的含义,在此上下文中 Python 2 和 Python 3 之间存在差异。 It's best visualized with a diff of the relevant docs entry ( Py2 vs. Py3 ):最好通过相关文档条目的差异( Py2与Py3 )进行可视化:
So while in Python 3 this definition includes only the exception being currently handled , in Python 2 also the most recently handled exception is included.因此,虽然在 Python 3 中,此定义仅包括当前正在处理的异常,但在 Python 2 中也包括最近处理的异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.