在Python中的错误恢复下一步 [英] On Error Resume Next in Python

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

问题描述

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



片段2



Snippet 2

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



片段3



Snippet 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,有一个名为的错误恢复下一步的声明。

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天全站免登陆