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

前端 未结 5 1255
[愿得一人]
[愿得一人] 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:00

    Can't be done if the call to bar is inside the try-block. Either you have to put the call outside of the try-except block, or use the else:

    try:
        foo()
    except:
        pass
    else:
        bar()
    

    If bar might throw an exception as well, you have to use a separate try block for bar.

    0 讨论(0)
  • 2021-01-05 10:00

    If you have just two functions, foo() bar(), check the other solutions. If you need to run A LOT of lines, try something like this example:

    def foo():
        raise Exception('foo_message')
    def bar():
        print'bar is ok'
    def foobar():
        raise  Exception('foobar_message')
    
    functions_to_run = [
         foo,
         bar,
         foobar,
    ]
    
    for f in functions_to_run:
        try:
            f()
        except Exception as e:
            print '[Warning] in [{}]: [{}]'.format(f.__name__,e)
    

    Result:

    [Warning] in [foo]: [foo_message]
    bar is ok
    [Warning] in [foobar]: [foobar_message]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-05 10:22

    That is not the intended way for try/except blocks to be used. If bar() should be executed even if foo() fails, you should put each in its own try/except block:

    try:
      foo()
    except:
      pass # or whatever
    
    try:
      bar()
    except:
      pass # or whatever
    
    0 讨论(0)
  • 2021-01-05 10:24

    Take bar() out of the try block:

    try:
        foo()
    except: 
        pass
    bar()
    

    Btw., watch out with catch-all except clauses. Prefer to selectively catch the exceptions that you know you can handle/ignore.

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