请编写一个函数,演示 `IndexError` 和 `StopIteration` 的不同,并说明它们分别在什么情况下会被触发。

# 演示 IndexError 和 StopIteration 的不同

# IndexError 示例
def demonstrate_index_error():
    # 定义一个列表
    my_list = [1, 2, 3]
    try:
        # 尝试访问超出列表范围的索引
        print(my_list[3])  # 正常索引范围是 0 到 2
    except IndexError as e:
        print(f"触发 IndexError: {e}")


# StopIteration 示例
def demonstrate_stop_iteration():
    # 定义一个迭代器
    my_iter = iter([1, 2, 3])
    try:
        # 手动调用 next() 直到耗尽迭代器
        print(next(my_iter))  # 1
        print(next(my_iter))  # 2
        print(next(my_iter))  # 3
        print(next(my_iter))  # 超出迭代范围
    except StopIteration as e:
        print(f"触发 StopIteration: {e}")


# 调用函数
if __name__ == "__main__":
    print("演示 IndexError:")
    demonstrate_index_error()
    print("\n演示 StopIteration:")
    demonstrate_stop_iteration()

IndexError 的解释

IndexError 是一种常见的错误,通常在以下情况下触发:

  1. 当试图访问一个序列(如列表、元组或字符串)中不存在的索引时。
    • 例如,列表 [1, 2, 3] 的有效索引是 0、1 和 2。如果尝试访问索引 3,就会触发 IndexError。
  2. 在切片操作中,如果提供的索引无效,也可能触发 IndexError,但这种情况较少见。

示例中的 demonstrate_index_error 函数展示了一个典型的场景:访问超出列表范围的索引。

StopIteration 的解释

StopIteration 是一种异常,用于表示迭代器已经耗尽,没有更多的元素可供迭代。通常在以下情况下触发:

  1. 当使用 next() 函数手动迭代一个迭代器时,如果迭代器没有更多元素,会抛出 StopIteration。
    • 例如,迭代器 iter([1, 2, 3]) 只有 3 个元素,调用 4 次 next() 后会触发 StopIteration。
  2. 在 for 循环中,Python 会自动处理 StopIteration,因此不会显式抛出。

示例中的 demonstrate_stop_iteration 函数展示了在手动调用 next() 时耗尽迭代器的场景。

两者的区别

  1. 触发场景:
    • IndexError 用于序列(如列表、元组)的索引访问越界。
    • StopIteration 用于迭代器耗尽时的信号。
  2. 用途:
    • IndexError 是程序中的错误,通常需要修复。
    • StopIteration 是迭代器的正常终止信号,通常由 Python 内部处理。
  3. 行为:
    • IndexError 会直接中断程序(除非捕获)。
    • StopIteration 可以被捕获,用于控制迭代流程。

总结

  • IndexError 和 StopIteration 都是 Python 中的异常,但它们的触发场景和用途完全不同。
  • 理解它们的区别有助于编写更健壮的代码,尤其是涉及序列操作和迭代器时。