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

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

    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]
    

提交回复
热议问题