返回从Python3中尝试除外

时间:2015-12-27 00:00:02

标签: python-3.x recursion return try-catch try-except

除了尝试使用新参数外,我怎样才能实现回归?

代码例如:

a = None
b = None
f = open('strings.data')    #1..99

for k in range(len(g)):
    k = int(k)
    #label: trytry
    try:
        main(cc = g[k], aa = a, bb = b)
    except error as e:
        if error.get('error_code') == 14:
            a = 1
            b = 2
            #goto trytry
    else:
        a = None
        b = None
        print(str(k) + 'Added #')

工作结果:

7  Added # 
8  Added # 
9  Added # 
10  Added # 
12  Added # 
13  Added # 
14  Added # 

第十一个元素捕获错误,因此未处理。 我希望得到你的帮助。谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用变量attempts再次尝试逻辑,最多attempts次:

a = None
b = None
f = open('strings.data')    #1..99

for k in range(len(g)):
    k = int(k)
    #label: trytry
    attempts = 5
    while attempts:
        try:
            main(cc = g[k], aa = a, bb = b)
        except error as e:
            if error.get('error_code') == 14:
                a = 1
                b = 2
                #goto trytry
                attempts -= 1
        else:
            a = None
            b = None
            print(str(k) + 'Added #')
            break

如果代码成功没有错误,则第一次尝试成功,不需要进一步尝试。但是如果确实发生了错误,那么您可以再次尝试,直到成功或者达到最大尝试次数(以先到者为准)。