[英]Is there a way to write the same try-except for multiple lines of code without hardcoding? python
我有多個函數可能會返回None
:
do_something()
, do_something2()
, do_something3()
等。
為了克服None類型錯誤,從代碼的另一部分開始,我必須對try-except
進行硬編碼,例如:
try:
x = do_other_things(do_something())
except someError: # because of None Type return
x = None
try:
y = do_other_things(do_something2())
except someError: # because of None Type return
y = None
有什么方法可以將相同的try-except
應用於不同的代碼行/不同的函數調用?
如果要測試相同的異常類型,則可以將try / except塊包裝到一個函數中,該函數接受其他函數和參數列表作為參數。
def try_except(myFunction, *params):
try:
return myFunction(*params)
except ValueError as e:
return None
except TypeError as e:
return None
我不是python專家,但是我可以換種方式。
創建一個函數數組並在循環中調用它們:
listOfFuncs = [do_something,do_something2,do_something3]
results = []*len(listOfFuncs)
for index, func in enumerate(listOfFuncs):
try:
results[index] = do_other_things(func())
except someError:
results[index] = None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.