1

我想问一下如何进行故障转移,如下所示:

 again = 1
 start = 1
 try:
   def countthis():
          for i in range (start,200):
              again = i
              print i
 except:
    print "Failure occured, I will try again" 
    start = again
    countthis.run()

我想如果 for 函数在 i 的 try 中失败,它会从最新的 i 重新启动(而不是从 1 开始)

4

2 回答 2

2

您可以使用这样的迭代器函数:

def countthis(start=0, end=100):
    for i in range(start, end):
        print i
        if i == 5:
            raise Exception('5 failed')
        yield i

然后在错误时使用下一个数字恢复计数器,跳过失败的:

ret = 0
end = 100
while ret < end - 1:
    try:
        for i in countthis(start=ret, end=end):
            ret = i
    except Exception, ex:
        print ex
        # when 5 reached, an exception will be raised, so here we restart at '6'
        ret = ret + 2

这将最终打印:

0
1
2
3
4
5
5 failed
6
7
......
99
于 2012-07-22T07:50:03.310 回答
0

正如我之前评论的那样,您可能希望将调用包装在 try..except 中,而不是定义中。这是你想要的?

def f():
    print "f called: ",

    import random
    x = random.randint(0, 10) / 8

    print "1/x =", 1/x

while True:
    try:
        f()
        break
    except ZeroDivisionError:
        print "f failed"
        continue

或者,如果您不想从 1 重新启动整个函数,为什么不在函数定义中使用 try..except :

def f():
    import random

    for i in range(1, 10):
        while True:
            try:
                print i,

                # do something with i:
                print 1 / (i // random.randint(0, 8))
                break
            except ZeroDivisionError:
                continue


f()
于 2012-07-22T06:49:11.157 回答