【问题标题】:StopIteration won't be caught in main()StopIteration 不会被 main() 捕获
【发布时间】:2020-12-18 14:22:48
【问题描述】:

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

当我直接发送到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 异常,而不是覆盖它。

【问题讨论】:

    标签: python python-3.x exception generator stopiteration


    【解决方案1】:

    Python 生成器在返回时会自动引发StopIteration。所以你不应该自己在生成器函数中引发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
    

    【讨论】:

    • 我无法返回False,我需要引发 StopIteration 异常。我正在使用带有 Iterator 类的 check_id_valid() 以及 main()
    • @Ileh 然后你需要在id_generator 中捕获StopIteration
    猜你喜欢
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 2010-10-14
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    相关资源
    最近更新 更多