On Error Resume Next in Python

后端 未结 7 1132
栀梦
栀梦 2020-12-11 02:07

Snippet 1

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

Snippet 2

try:
    do_mag         


        
相关标签:
7条回答
  • 2020-12-11 02:24

    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...
    
    0 讨论(0)
  • 2020-12-11 02:28

    A lot of ident, but it works

    try:
        do_magic()
    finally:
        try:
            do_foo()
        finally:
            try:
                do_bar()
            finally:
                pass
    
    0 讨论(0)
  • 2020-12-11 02:31

    If there are no parameters...

    funcs = do_magic, do_foo, do_bar
    
    for func in funcs:
        try:
            func()
        except:
            continue
    
    0 讨论(0)
  • 2020-12-11 02:33

    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
    
    0 讨论(0)
  • 2020-12-11 02:35

    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 :|

    0 讨论(0)
  • 2020-12-11 02:42

    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.

    0 讨论(0)
提交回复
热议问题