建議使用更簡潔的方式來處理 Python 異常?


無論是否丟擲異常,我們都可以使用 finally 子句進行清除

try:
  #some code here
except:
  handle_exception()
finally:
  do_cleanup()

如果異常發生時需要進行清除,我們可以編寫如下程式碼

should_cleanup = True
try:
  #some code here
  should_cleanup = False
except:
  handle_exception()
finally:
  if should_cleanup():
    do_cleanup()

更新於: 2019 年 9 月 27 日

138 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.