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
异常,而不是覆盖它。