0
由於例外對於慣用Python來說非常重要,如果表達式的評估結果爲異常,那麼執行特定代碼塊的乾淨方式是否爲或?通過乾淨,我的意思是一個易於閱讀的Pythonic,而不是重複代碼塊?如果條件或異常執行代碼塊
例如,而不是:
try:
if some_function(data) is None:
report_error('Something happened')
except SomeException:
report_error('Something happened') # repeated code
可以這樣乾淨改寫,使report_error()
不寫了兩次?
(類似的問題:How can I execute same code for a condition in try block without repeating code in except clause但這是在那裏可以通過一個簡單的測試if語句內避免異常的具體情況)