在 python 中,我有一個呼叫的函式func(),它可以引發NoSuchElementException:我試圖用input1如果不正確呼叫它,用input2else 放棄呼叫它。
為了清楚起見,有沒有更好的方法來撰寫此代碼:
submit_button = None
try:
submit_button = func(input1)
except NoSuchElementException:
try:
submit_button = func(input2)
except NoSuchElementException:
pass
uj5u.com熱心網友回復:
您可以執行以下操作:
for i in [input1, input2]:
try:
submit_button = func(i)
break
except NoSuchElementException:
print(f"Input {i} failed")
else:
print("None of the options worked")
如果第一個輸入沒有引發例外,則中斷回圈,否則保持回圈并嘗試第二個輸入。
這樣,您可以嘗試任意數量的輸入,只需將它們添加到串列中
如果您從未中斷回圈,則最后的 else 將執行,這意味著所有選項都不起作用
如果您想嘗試多個輸入并平等對待它們,這很有效。對于只有兩個輸入,您的代碼對我來說看起來足夠可讀。(試試這個,如果它不起作用試試那個)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/449021.html
標籤:Python python-3.x 例外 试着抓
上一篇:強制運行特定方法
下一篇:去除例外值
