How to continue with next line in a Python's try block?

前端 未结 5 1301
[愿得一人]
[愿得一人] 2021-01-05 09:30

e.g.

try:
    foo()
    bar()
except: 
    pass

When foo function raise an exception, how to skip to the next line (bar) and execute it?

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-05 10:18

    If you want exceptions from both functions to be handled by the same except clause, then use an inner try/finally block:

    try:
        try:
            foo()
        finally:
            bar()
    except Exception:
        print 'error'
    

    If there is an exception in foo(), first bar() will be executed, then the except clause.

    However, it's generally good practice to put the minimum amount of code inside a try block, so a separate exception handler for each function might be best.

提交回复
热议问题