假設我有一些代碼:
try :
JumpOverFence()
except TooShortError :
print("Wow, you're too short for this obstacle")
ABunchOfLinesThatSaysGoTrain()
except FellError :
print("Wow, you fell! go work on your balance!")
ABunchOfLinesThatSaysGoTrain()
所以基本上我只有一堆我想運行的行,不管錯誤如何,還有幾行我想為特定型別的例外運行,希望我很清楚。謝謝!
uj5u.com熱心網友回復:
我只是想到了這樣一個事實,即我可以使用一個finally塊來放置執行的“強制”部分,因為除了我所做的類比之外,我的用例中的代碼如下所示:
try :
CopyDataFromAWebsite()
PasteData() #This line won't execute if the website crashes let's say
except WebsiteCrash :
#Print some things
PasteData()
所以我能做的是:
try :
CopyDataFromWebsite()
except WebsiteCrash :
#print some lines
finally :
PasteData()
這樣我可以確保無論發生什么都執行這個函式,但我必須承認,這是一個非常罕見的用例..
uj5u.com熱心網友回復:
寫一個函式。
def GoTrain(msg):
print(msg)
print("Go do some training!")
# more lines here
try :
JumpOverFence()
except TooShortError :
GoTrain("Wow, you're too short for this obstacle")
except FellError :
GoTrain("Wow, you fell! go work on your balance!")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489149.html
上一篇:(python)用戶定義的例外不起作用,使用類{不知道為什么當我輸入字串時例外不起作用}
下一篇:Junit沒有得到自定義例外
