python - 生成器方法 throw 的返回值

标签 python generator return-value yield throw

throw 的帮助说:

builtins.generator 实例的 throw(...) 方法 throw(typ[,val[,tb]]) -> 在生成器中引发异常, 返回下一个产生的值或引发 StopIteration

“返回下一个产生的值”这是我的问题!

让我们看一下这个例子:

def gen():
    counter = 1
    while True:
        try:
            yield counter
            counter += 1
        except Exception as e:
            print("Exception and tpye: ", e, type(e))
            

x = gen()
print("Result of first next call: ", next(x))
res = x.throw(ValueError("Whatever!"))
print("result of throw call: ", res)
print("Result of first next call: ", next(x))

输出看起来像这样:

Result of first next call:  1
Exception and tpye:  Whatever! <class 'ValueError'>
result of throw call:  1
Result of first next call:  2

throw的返回值不应该是2而不是1吗?帮助文件说“return NEXT yielded value2”不是“return again previously yielded value”

我担心我完全错了?

最佳答案

当您使用 gen.throw(...) 时,异常会在 yield 语句中引发。

当您捕获它时,不会执行以下计数器增量。您可以将它移到 finally: 子句中,以确保无论如何,您始终会增加 counter:

def gen():
    counter = 1
    while True:
        try:
            yield counter
        except Exception as e:
            print("Exception and type: ", e, type(e))
        finally:
            counter += 1

关于python - 生成器方法 throw 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64151787/

相关文章:

python - 查找在模块中明确定义的函数(python)

python - 如何使用 swig 包装器调用 C++ 类指针上的方法?

python - 当在 Python 中创建一个类并使用引用它的对象时,您将如何使用该类中的对象名称?

error-handling - 用 Jest 捕捉错误时如何测试 Redux-Saga

python - 从经常更新的文件中读取

JavaScript 为什么 getItem() 有两种返回类型?

python - scrapy可以从python中具有多个类的标签中找到类

python - 如何解决 Python 中的 StopIteration 错误?

c++ - 代码值应该每次都更改,因此不会显示相同的座位,但不会显示

c++ - 在 C++ 中传递/检索指针