[英]How to access re-raised exception in Python 3?
在Python 3中,有一個有用的raise ... from ...
功能來重新引發異常。 也就是說,如何從引發的異常中找到原始(/重新引發的)異常? 這是一個(帶有愚蠢的)示例,上面有注釋以說明我的意思-
def some_func():
try:
None() # TypeError: 'NoneType' object is not callable
except as err:
raise Exception("blah") from err
try:
some_func()
except as err:
# how can I access the original exception (TypeError)?
它在引發的異常的__cause__
屬性中。 摘自對文檔raise
聲明 ,它說關於raise ... from ...
:
from
子句用於異常鏈接:如果給定,第二個表達式必須是另一個異常類或實例, 然后將其作為__cause__
屬性 (可寫) 附加到引發的異常上 。 如果未處理引發的異常,則將打印兩個異常。
因此,在給定的情況下, repr
__cause__
屬性:
def some_func():
try:
None() # TypeError: 'NoneType' object is not callable
except TypeError as err:
raise Exception("blah") from err
try:
some_func()
except Exception as er:
print(repr(er.__cause__))
將打印出:
TypeError("'NoneType' object is not callable",)
每當從異常處理程序( except
子句)引發異常時,原始異常都會保留在新異常的__context__
。
每當使用from
語法引發異常時,在from
指定的異常將保存在新異常的__cause__
屬性中。
在通常的用例中,這等於包含原始異常的__cause__
和__context__
:
def f():
try:
raise Exception('first exception')
except Exception as e:
raise Exception('second exception') from e
try:
f()
except Exception as e:
print('This exception', e)
print('Original exception', e.__context__)
print('Also original exception', e.__cause__)
這也是設置__context__
的示例:
try:
raise Exception('first exception')
except Exception as e:
raise Exception('second exception')
以及設置__cause__
的時間的示例:
e = Exception('first exception')
raise Exception('second exception') from e
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.