如何在 Python 中捕獲 StopIteration 異常?


當迭代器完成,它的 next 方法會引發 StopIteration。該異常不被認為是一個錯誤。

我們透過以下方式重寫給定程式碼以捕獲異常並得知其型別。

示例

import sys
try:
z = [5, 9, 7]
i = iter(z)
print i
print i.next()
print i.next()
print i.next()
print i.next()
except Exception as e:
print e
print sys.exc_type

輸出

<listiterator object at 0x0000000002AF23C8>
5
9
7
<type 'exceptions.StopIteration'>


更新時間:2020-02-12

1000+ 次觀看

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.