In the question, Snippet 3 does not work, but will work if you do not mind splitting each line into two lines ...
try: do_magic() except: pass try: do_foo() except: pass try: do_bar() except: pass
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 it in test.py and then at the CMD prompt on Windows just type test.py , it will return No_Arg1 No_Arg2 No_Arg3 because there were no arguments. However, if you specify some arguments, if the type test.py 111 222 will be returned 111 222 No_Arg3 , etc. (Tested - Windows 7, python2.7).
IMHO it is much more elegant than answers to examples of nesting. It also works in exactly the same way as "Error while retrying next", and I use it when translating from VB6. One problem is that try strings cannot contain conditionals. I found that, as a rule, python cannot contain more than one : per line. However, this simply means splitting the statement into 3 lines, etc.
source share