代码之家  ›  专栏  ›  技术社区  ›  None

在python中成功运行try语句时运行代码

  •  24
  • None  · 技术社区  · 16 年前

    我想知道在python中,如果try语句成功了,而try语句本身却没有这样一种简单的方法来运行代码。else或finally命令就是这么做的(我不理解它们的文档)?我知道我可以使用这样的代码:

    successful = False
    try:
        #code that might fail
        successful = True
    except:
        #error handling if code failed
    if successful:
        #code to run if try was successful that isn't part of try
    

    但我想知道有没有更短的路。

    3 回复  |  直到 16 年前
        1
  •  67
  •   MendelG    5 年前

    你想要什么 else

    for i in [0, 1]:
        try:
            print '10 / %i: ' % i, 10 / i
        except:
            print 'Uh-Oh'
        else:
            print 'Yay!'
    
        2
  •  18
  •   unutbu    16 年前

    你在找 else

    try:
        #code that might fail
    except SomeException:
        #error handling if code failed
    else:
        # do this if no exception occured
    
        3
  •  -3
  •   Zee Spencer    16 年前

    try块应该是要执行的代码,而except应该终止程序。我需要更好地理解你的目标才能给出更好的答案。