try except StopIteration
时间: 2024-05-06 15:20:26 浏览: 92
Python标准异常和异常处理详解
The "try-except" block is a Python construct used for error handling. "StopIteration" is a built-in Python exception that is raised to signal the end of an iteration.
Here is an example of how "try-except" and "StopIteration" can be used together:
```
numbers = [1, 2, 3, 4, 5]
iterator = iter(numbers)
while True:
try:
num = next(iterator)
print(num)
except StopIteration:
break
```
This code creates an iterator for the list of numbers, and then uses a while loop to iterate over the numbers one at a time. The "try" block attempts to get the next number in the iterator using the "next()" function. If there are no more numbers, a "StopIteration" exception is raised and caught in the "except" block. The loop is then terminated using the "break" keyword.
阅读全文