python catch exception and continue try block

2020-05-14 07:56发布

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()
except:
    pass

vs

try:
    do_smth1()
    do_smth2()
except:
    ??? # magic word to proceed to do_smth2() if there was exception in do_smth1

9条回答
Summer. ? 凉城
2楼-- · 2020-05-14 08:31

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!

查看更多
成全新的幸福
3楼-- · 2020-05-14 08:32

Depending on where and how often you need to do this, you could also write a function that does it for you:

def live_dangerously(fn, *args, **kw):
    try:
        return fn(*args, **kw)
    except Exception:
        pass

live_dangerously(do_smth1)
live_dangerously(do_smth2)

But as other answers have noted, having a null except is generally a sign something else is wrong with your code.

查看更多
三岁会撩人
4楼-- · 2020-05-14 08:41

While the other answers and the accepted one are correct and should be followed in real code, just for completeness and humor, you can try the fuckitpy ( https://github.com/ajalt/fuckitpy ) module.

Your code can be changed to the following:

@fuckitpy
def myfunc():
    do_smth1()
    do_smth2()

Then calling myfunc() would call do_smth2() even if there is an exception in do_smth1())

Note: Please do not try it in any real code, it is blasphemy

查看更多
登录 后发表回答