Handle an exception thrown in a generator

前端 未结 4 738
猫巷女王i
猫巷女王i 2020-12-01 13:23

I\'ve got a generator and a function that consumes it:

def read():
    while something():
        yield something_else()

def process():
    for item in read         


        
4条回答
  •  悲哀的现实
    2020-12-01 14:24

    When a generator throws an exception, it exits. You can't continue consuming the items it generates.

    Example:

    >>> def f():
    ...     yield 1
    ...     raise Exception
    ...     yield 2
    ... 
    >>> g = f()
    >>> next(g)
    1
    >>> next(g)
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 3, in f
    Exception
    >>> next(g)
    Traceback (most recent call last):
      File "", line 1, in 
    StopIteration
    

    If you control the generator code, you can handle the exception inside the generator; if not, you should try to avoid an exception occurring.

提交回复
热议问题