2

StopIteration当我发送的数字大于 999999999 时,我想引发异常。

当我print(check_id_valid(1234567980))直接发送到函数参数或IDIterator类(迭代器class)并从那里将数字传递给 check_id_valid()函数时,异常会被捕获main()。打印错误字符串:

Reached max number, 1234567980 is over 9 digits

但是当我将号码发送到id_generator()功能时(感谢之前的帮助,它运行良好),

StopIteration异常不会在main()

def check_id_valid(id_number):

     if len(str(id_number)) < 9:
         raise illigalException(id_number)        
     if int(id_number) > 999999999:
         raise StopIteration(id_number)
def id_generator(Id_number):
   while True:
       Id_number += 1
       if check_id_valid(Id_number):
           yield Id_number
def main():
 
    id_gen = id_generator(1234567800)
    try:
        for item in range(10):   
            print(next(id_gen))

    except StopIteration as e:
        print("Reached max number, " + str(e)  + " is over 9 digits")
    except (illigalException) as e:
        print(e)

if __name__ == "__main__":
    main()

错误信息是 -

raise StopIteration(id_number) StopIteration: 1234567801 The above exception was the direct cause of the following exception:

print(next(id_gen)) RuntimeError: generator raised StopIteration

我该如何解决?

附言

我需要使用构建的StopIteration异常,而不是覆盖它。

4

1 回答 1

1

StopIterationPython 生成器在返回时会自动引发。所以你不应该StopIteration自己在生成器函数中引发。

用于迭代器StopIteration中以停止迭代,例如在 for 循环中。

def check_id_valid(id_number):

     if len(str(id_number)) < 9:
         raise illigalException(id_number)        
     if int(id_number) > 999999999:
         return False

     # you need to return True if is valid.
     return True


def id_generator(Id_number):
   while True:
       Id_number += 1
       if check_id_valid(Id_number):
           yield Id_number
       
       else:
           # this return here will raise the StopIteration error with message id_number for you.
           return id_number
          

更新

# assuming your check_id_valid is still the same.
def id_generator(Id_number):
    while True:
        Id_number += 1
        try:
            check_id_valid(Id_number)
        except StopIteration:
            # this return will raise StopIteration when you call next() on id_generator
            return Id_number
        except Exception as e:
            # raise the other illigalException 
            raise e
        
        yield Id_number
于 2020-08-30T05:47:55.897 回答