Python 中的错误继续下一步 [英] On Error Resume Next in Python

查看:31
本文介绍了Python 中的错误继续下一步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

do_magic() # Throws exception, doesn't execute do_foo and do_bar
do_foo()
do_bar()

片段 2

try:
    do_magic() # Doesn't throw exception, doesn't execute do_foo and do_bar
    do_foo() 
    do_bar()
except:
    pass

代码段 3

try: do_magic(); except: pass
try: do_foo()  ; except: pass
try: do_bar()  ; except: pass

有没有办法优雅地编写代码片段 3?

Is there a way to write code snippet 3 elegantly?

  • 如果 do_magic() 失败与否,do_foo()do_bar() 应该被执行.
  • 如果 do_foo() 失败与否,do_bar() 应该被执行.
  • if do_magic() fails or not, do_foo() and do_bar() should be executed.
  • if do_foo() fails or not, do_bar() should be executed.

在 Basic/Visual Basic/VBS 中,有一个名为 On Error Resume Next 的语句可以执行此操作.

In Basic/Visual Basic/VBS, there's a statement called On Error Resume Next which does this.

推荐答案

在 Python 3.4 以后,您可以使用 contextlib.suppress:

In Python 3.4 onwards, you can use contextlib.suppress:

from contextlib import suppress

with suppress(Exception): # or, better, a more specific error (or errors)
    do_magic()
with suppress(Exception):
    do_foo()
with suppress(Exception):
    do_bar()

或者,fuckit.

这篇关于Python 中的错误继续下一步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆