簡體   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