do_magic() # Throws exception, doesn\'t execute do_foo and do_bar
do_foo()
do_bar()
try:
do_mag
If you are the one coding the fucntions, why not program the functions to return status codes? Then they will be atomic and you wont have to capture the error in the main section. You will also be able to perform roll back or alternate coding on failure.
def do_magic():
try:
#do something here
return 1
except:
return 0
in main program..
if do_magic() = 0:
#do something useful or not...
if do_foo() = 0:
#do something useful or not...
if do_bar() = 0:
#do something useful or not...
A lot of ident, but it works
try:
do_magic()
finally:
try:
do_foo()
finally:
try:
do_bar()
finally:
pass
If there are no parameters...
funcs = do_magic, do_foo, do_bar
for func in funcs:
try:
func()
except:
continue
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
you could try a nested ´try´ loop, alltho that might not be as elegantly pythonic as you might want. the ´lambda´ solution is is also a good way to go, did not mention because it was done in the previous answer
edit:
try:
do_magic()
finally:
try:
do_foo()
finally:
try:
do_bar()
except:
pass
edit 2:
well damnnit, this answer just got posted seconds beforehand again :|
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.