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
Is there a way to write code snippet 3 elegantly?
do_magic()
fails or not, do_foo()
and do_bar()
should be executed.do_foo()
fails or not, do_bar()
should be executed.In Basic/Visual Basic/VBS, there's a statement called On Error Resume Next
which does this.
On Error Resume Next Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred and execution continues. Use this form rather than On Error GoTo when accessing objects.
The SyntaxError: continue not properly in loop error is raised when you try to use a continue statement outside of a for loop or a while loop. To fix this error, enclose any continue statements in your code inside a loop.
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()
Alternatively, fuckit
.
If all three functions accept same number of parameters:
for f in (do_magic, do_foo, do_bar):
try:
f()
except:
pass
Otherwise, wrap the function call with lambda
.
for f in (do_magic, lambda: do_foo(arg1, arg2)):
try:
f()
except:
pass
If there are no parameters...
funcs = do_magic, do_foo, do_bar
for func in funcs:
try:
func()
except:
continue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With