[英]How do you raise an exception inside an except block without exception chaining in a way that's compatible with both Python 2 and 3?
在 Python 2.7 中,以下將僅打印一個回溯,來自except
塊中引發的異常:
try:
1/0
except ZeroDivisionError:
raise Exception("Error!")
Output:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
Exception: Error!
但是在 Python 3 中存在異常鏈接。 這是相同代碼的 output:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
Exception: Error!
我需要編寫一些與 Python 2.7 和 Python 3 兼容的代碼,並且當在該except
塊內引發異常時,我需要沒有異常鏈接。 因此,當在 Python 2.7 中執行該代碼時,output 將是您在上面看到的。
我發現的一種可能的解決方案是raise_from
,包含在six
模塊中:
from six import raise_from
try:
1/0
except ZeroDivisionError:
raise_from(Exception("Error!"), None)
但是,它在我想避免的回溯中為raise_from
添加了額外的一行:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<string>", line 3, in raise_from
Exception: Error!
有沒有辦法做到這一點?
如果您使用完整路徑調用它,以下會在 py2.7.13 和 py3.9.2 上生成相同的 output。 (如果使用相對路徑,py3 會擴展它,但 py2 不會。)
try:
1/0
except ZeroDivisionError:
internal = Exception("Error!")
internal.__suppress_context__ = True
raise internal
回溯(最近一次通話最后):
文件“b:\development\python\so.py”,第 6 行,在
提高內部
例外:錯誤!
我希望避免可能更改的內部屬性,但 __suppress_context__ 已記錄在案 https://docs.python.org/3/library/exceptions.ZFC35FDC70D5FC69D2698Z83A822C7A5E3
在引發異常后,使用finally
塊丟棄上下文:
try:
1/0
except ZeroDivisionError:
# store exception to allow modifying it
exc = Exception("Error!")
try:
raise exc
finally:
# context has been set here already – discard it
exc.__context__ = None
這在 Python2 中也適用於任何適當的異常,即那些從BaseException
派生的異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.