[英]Python: Multiple try except blocks in one?
有沒有一種巧妙的方法可以在 try 塊中使用乘法命令,以便它基本上嘗試每一行而不會在一個命令產生錯誤時立即停止?
基本上我想替換這個:
try:
command1
except:
pass
try:
command2
except:
pass
try:
command3
except:
pass
有了這個:
try all lines:
command1
command2
command3
except:
pass
定義一個列表以便我可以遍歷命令似乎是一個糟糕的解決方案
我會說這是一種設計氣味。 消除錯誤通常是一個壞主意,特別是如果您要消除很多錯誤。 但我會給你懷疑的好處。
您可以定義一個包含try/except
塊的簡單函數:
def silence_errors(func, *args, **kwargs):
try:
func(*args, **kwargs)
except:
pass # I recommend that you at least log the error however
silence_errors(command1) # Note: you want to pass in the function here,
silence_errors(command2) # not its results, so just use the name.
silence_errors(command3)
這有效並且看起來相當干凈,但是您需要在任何地方不斷重復silence_errors
。
list 解決方案沒有任何重復,但看起來有點糟糕,並且您無法輕松傳入參數。 但是,您可以從程序中的其他位置讀取命令列表,這可能會有所幫助,具體取決於您在做什么。
COMMANDS = [
command1,
command2,
command3,
]
for cmd in COMMANDS:
try:
cmd()
except:
pass
除非我完全誤解你,否則應該這樣做:
try:
thing1
thing2
thing3
except:
pass
try
塊可以包含任意數量的語句。
我使用不同的方式,使用一個新變量:
continue_execution = True
try:
command1
continue_execution = False
except:
pass
if continue_execution:
try:
command2
except:
command3
要添加更多命令,您只需添加更多這樣的表達式:
try:
commandn
continue_execution = False
except:
pass
實際上,您的第二選擇正是您想要的帽子。 一旦任何命令引發異常,它就會傳遞到except,並包含有關哪個異常以及發生在哪一行的信息。 如果需要,您可以捕獲不同的異常並使用
try:
command1
command2
except ExceptionONe:
pass
except Exception2:
pass
except:
pass # this gets anything else.
您可以在同一個 except 語句中排除多個錯誤。例如:
try:
cmd1
cmd2
cmd3
except:
pass
或者你可以創建一個函數並傳遞錯誤和 cmd
def try_except(cmd):
try:
cmd
except:
pass
實際上,我認為他希望以更好的方式實現以下目標:
try:
command1
except:
try:
command2
except:
try:
command3
except:
pass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.