如何在 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'>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP