0

有没有办法在 Python 中执行以下操作?

try:
  Thing1()
try_this_too:
  Thing2()
try_this_too:
  Thing3()
except:
  print "Nothing worked :-("

请注意,如果 Thing1() 成功,我不想做任何其他事情。

4

3 回答 3

8
for thing in (Thing1,Thing2,Thing3):
    try:
       thing()
       break  #break out of loop, don't execute else clause
    except:   #BARE EXCEPT IS USUALLY A BAD IDEA!
       pass
else:
    print "nothing worked"
于 2013-03-01T16:01:46.857 回答
4

这很容易扩展到任意数量的功能:

funcs = (Thing1, Thing2, Thing3)

failures = 0

for func in funcs:
    try:
       func()
       break
    except Exception:
       failures += 1

if failures == len(funcs):
    print "Cry evrytime :-("
于 2013-03-01T16:01:09.280 回答
1
try:
  Thing1()
except:
  try:
     Thing2()
  except:
     try:
        Thing3()
     except:
        print "Nothing worked :-("
于 2013-03-01T15:59:44.750 回答