On Error Resume Next in Python

2019-01-27 20:14发布

Snippet 1

do_magic() # Throws exception, doesn't execute do_foo and do_bar
do_foo()
do_bar()

Snippet 2

try:
    do_magic() # Doesn't throw exception, doesn't execute do_foo and do_bar
    do_foo() 
    do_bar()
except:
    pass

Snippet 3

try: do_magic(); except: pass
try: do_foo()  ; except: pass
try: do_bar()  ; except: pass

Is there a way to write code snippet 3 elegantly?

  • if do_magic() fails or not, do_foo() and do_bar() should be executed.
  • if do_foo() fails or not, do_bar() should be executed.

In Basic/Visual Basic/VBS, there's a statement called On Error Resume Next which does this.

7条回答
冷血范
2楼-- · 2019-01-27 20:46

If you are the one coding the fucntions, why not program the functions to return status codes? Then they will be atomic and you wont have to capture the error in the main section. You will also be able to perform roll back or alternate coding on failure.

def do_magic():
    try:
        #do something here
        return 1
    except:
        return 0

in main program..

if do_magic() = 0:
   #do something useful or not...

if do_foo() = 0:
   #do something useful or not...

if do_bar() = 0:
   #do something useful or not...
查看更多
登录 后发表回答