简体   繁体   中英

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.

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 -

Exception not found
Exception found
Exception found

When run on python 3, the exception is not detected.
Output generated by python 3.7.7 -

Exception not found
Exception not found
Exception not found

Why does python 2 behave this way? Is there any workaround in python 2 to avoid this behavior?
Wrong exception detection is throwing off my application's logging when run using gunicorn.

Regarding the meaning of "handling an exception" there is a difference between Python 2 and Python 3 in this context. It's best visualized with a diff of the relevant docs entry ( Py2 vs. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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