在 python 腳本中,如果我們在一個運算式中有多個串列,例如:
a[1] = b[2] c[3] d[4]
或者
a[1] = b[c[d[1]]] # (This case added in EDIT)
現在,這些串列之一拋出錯誤,IndexError: List Index Out of Range 因為索引高于串列長度。
有沒有辦法使用try/except陳述句來改進這種默認的例外處理,以便我們可以立即找出導致問題的串列?
否則,需要使用命令列除錯器檢查每個串列。我了解如果有可用的 IDE,則此功能可能已內置到 IDE 中。
uj5u.com熱心網友回復:
最簡單的方法是人為地將這條線分成幾條線。例如:
b =[1]
c = []
d = [1]
a = b[0] \
c[0] \
d[0]
Traceback (most recent call last):
File "/tmp/foo.py", line 7, in <module>
c[0] \
IndexError: list index out of range
uj5u.com熱心網友回復:
另一種選擇是使用inspect模塊來查找引發錯誤的行號。這需要您修改添加 分配以使用先前定義的本地變數bv = b[2],如所示,否則將其拆分為單獨的行。
a = [1, 2, 3]
b = [1] * 3
c = [2] * 3
d = [3] * 5
try:
a[1] = b[2] \
c[3] \
d[4]
except IndexError:
from inspect import trace
var = trace()[0].code_context[0].split('=', 1)[-1].split('[', 1)[0].lstrip(' -*')
print(f'The variable that raised the IndexError was: {var}')
出去:
The variable that raised the IndexError was: c
有趣的事實:以下語法,我實際上認為是良好的編碼實踐,實際上并沒有像您想要的資訊堆疊跟蹤那樣表現。不幸的是,我不知道為什么。
a[1] = b[2] \
c[3] \
d[4]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/366165.html
上一篇:使用Wekaforjava呼叫buildClassifier時為什么會出現運行時例外?
下一篇:服務系結器例外:找不到方法
