簡體   English   中英

如何以與 Python 2 和 3 兼容的方式在沒有異常鏈接的情況下在 except 塊內引發異常?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM