内容简介:翻译自:https://stackoverflow.com/questions/26059424/on-error-resume-next-in-python
片段1
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?
>如果do_magic()失败或不执行,则应执行do_foo()和do_bar().
>如果do_foo()失败或不执行,则应执行do_bar().
在Basic / Visual Basic / VBS中,有一个名为On Error Resume Next的语句执行此操作.
在 Python 3.4及更高版本中,您可以使用
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
.
翻译自:https://stackoverflow.com/questions/26059424/on-error-resume-next-in-python
以上所述就是小编给大家介绍的《On Error在Python中继续下一步》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Head First 设计模式(中文版)
弗里曼 / O'Reilly Taiwan公司 / 中国电力出版社 / 2007-9 / 98.00元
《Head First设计模式》(中文版)共有14章,每章都介绍了几个设计模式,完整地涵盖了四人组版本全部23个设计模式。前言先介绍这本书的用法;第1章到第11章陆续介绍的设计模式为Strategy、Observer、Decorator、Abstract Factory、Factory Method、Singleton,Command、Adapter、Facade、TemplateMethod、I......一起来看看 《Head First 设计模式(中文版)》 这本书的介绍吧!