python catch exception and continue try block

前端 未结 9 2438
眼角桃花
眼角桃花 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条回答
  •  死守一世寂寞
    2020-11-29 01:23

    You can achieve what you want, but with a different syntax. You can use a "finally" block after the try/except. Doing this way, python will execute the block of code regardless the exception was thrown, or not.

    Like this:

    try:
        do_smth1()
    except:
        pass
    finally:
        do_smth2()
    

    But, if you want to execute do_smth2() only if the exception was not thrown, use a "else" block:

    try:
        do_smth1()
    except:
        pass
    else:
        do_smth2()
    

    You can mix them too, in a try/except/else/finally clause. Have fun!

提交回复
热议问题