On Error Resume Next in Python

后端 未结 7 1133
栀梦
栀梦 2020-12-11 02:07

Snippet 1

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

Snippet 2

try:
    do_mag         


        
相关标签:
7条回答
  • 2020-12-11 02:45

    In the question, Snippet 3 does not work but will work if you don't mind splitting each line over two lines...

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

    A working example..

    import sys
    a1 = "No_Arg1"
    a2 = "No_Arg2"
    a3 = "No_Arg3"
    try: a1 = sys.argv[1]
    except: pass
    try: a2 = sys.argv[2]
    except: pass
    try: a3 = sys.argv[3]
    except: pass
    
    print a1, a2, a3
    

    ..if you save this to test.py and then at a CMD prompt in windows simply type test.py it will return No_Arg1 No_Arg2 No_Arg3 because there were no arguments. However, if you supply some arguments, if type test.py 111 222 it will return 111 222 No_Arg3 etc. (Tested - Windows 7, python2.7).

    IMHO this is far more elegant than the nesting example replies. It also works exactly like On Error Resume Next and I use it when translating from VB6. One issue is that the try lines cannot contain a conditional. I have found that as a rule, python cannot contain more than one : in a line. That said, it simply means splitting the statement over 3 lines etc.

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