在這個例子中
try:
raise ValueError
except ValueError as e:
raise IndexError from e
追溯記錄
...
ValueError:
The above exception was the direct cause of the following exception:
IndexError
...
如果我要捕獲IndexError,我將如何檢查回溯以發現它是由 引起的ValueError?
uj5u.com熱心網友回復:
根據PEP 3134,在例外中raise ... from設定屬性。__cause__您可以訪問:
try:
try:
raise ValueError
except ValueError as e:
raise IndexError from e
except IndexError as ee:
print(type(ee.__cause__))
結果:
<class 'ValueError'>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/512974.html
標籤:Python例外
