建议使用更简洁的方式来处理 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 次浏览

开启你的职业生涯

通过完成课程获得认证

开始
广告