[英]Better way to use try except block
我有一個執行多個Python語句的要求,即使執行失敗,我也很少希望執行其余的語句。
目前,我正在做:
try:
wx.StaticBox.Destroy()
wx.CheckBox.Disable()
wx.RadioButton.Enable()
except:
pass
如果任何一條語句失敗,則將執行except
,程序退出。 但是我需要的是即使失敗,它也應該運行所有三個語句。
如何在Python中執行此操作?
在要調用的方法上使用for
循環,例如:
for f in (wx.StaticBox.Destroy, wx.CheckBox.Disable, wx.RadioButton.Enable):
try:
f()
except Exception:
pass
請注意,此處我們使用的是except Exception
,這通常比您想要的except更可能。
如果在try
塊期間發生異常,則跳過該塊的其余部分。 您應該為三個單獨的語句使用三個單獨的try
子句。
添加以回應評論:
由於您顯然想處理許多語句,因此可以使用包裝器方法檢查異常:
def mytry(functionname):
try:
functionname()
except Exception:
pass
然后以您的函數名稱作為輸入來調用該方法:
mytry(wx.StaticBox.Destroy)
我建議創建一個上下文管理器類,該類禁止任何異常以及要記錄的異常。
請查看下面的代碼。 將鼓勵對此進行任何改進。
import sys
class catch_exception:
def __init__(self, raising=True):
self.raising = raising
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
if issubclass(type, Exception):
self.raising = False
print ("Type: ", type, " Log me to error log file")
return not self.raising
def staticBox_destroy():
print("staticBox_destroy")
raise TypeError("Passing through")
def checkbox_disable():
print("checkbox_disable")
raise ValueError("Passing through")
def radioButton_enable():
print("radioButton_enable")
raise ValueError("Passing through")
if __name__ == "__main__":
with catch_exception() as cm:
staticBox_destroy()
with catch_exception() as cm:
checkbox_disable()
with catch_exception() as cm:
radioButton_enable()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.