python catch exception and continue try block

前端 未结 9 2446
眼角桃花
眼角桃花 2020-11-29 00:59

Can I return to executing try-block after exception occurs? (The goal is to write less) For Example:

try:
    do_smth1()
except:
    pass

try:
    do_smth2(         


        
9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 01:20

    one way you could handle this is with a generator. Instead of calling the function, yield it; then whatever is consuming the generator can send the result of calling it back into the generator, or a sentinel if the generator failed: The trampoline that accomplishes the above might look like so:

    def consume_exceptions(gen):
        action = next(gen)
        while True:
            try:
                result = action()
            except Exception:
                # if the action fails, send a sentinel
                result = None
    
            try:
                action = gen.send(result)
            except StopIteration:
                # if the generator is all used up, result is the return value.
                return result
    

    a generator that would be compatible with this would look like this:

    def do_smth1():
        1 / 0
    
    def do_smth2():
        print "YAY"
    
    def do_many_things():
        a = yield do_smth1
        b = yield do_smth2
        yield "Done"
    
    >>> consume_exceptions(do_many_things())
    YAY
    

    Note that do_many_things() does not call do_smth*, it just yields them, and consume_exceptions calls them on its behalf

提交回复
热议问题