do_magic() # Throws exception, doesn't execute do_foo and do_bar do_foo() do_bar()
try: do_magic() # Doesn't throw exception, doesn't execute do_foo and do_bar do_foo() do_bar() except: pass
try: do_magic(); except: pass try: do_foo() ; except: pass try: do_bar() ; except: pass
有没有一种方法可以优雅地编写代码片段3?
do_magic()
do_foo()
do_bar()
在Basic / Visual Basic / VBS中,有一个调用On Error Resume Next此操作的语句。
On Error Resume Next
从Python 3.4开始,您可以使用contextlib.suppress:
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。
fuckit