这也是我不确定是否正确/优雅处理的事情。
我要做的是从生成器中获取
yield一个
Exception,然后将其提升到其他位置。喜欢:
class myException(Exception): def __init__(self, ...) ...def g(): ... if everything_is_ok: yield result else: yield myException(...)my_gen = g()while True: try: n = next(my_gen) if isinstance(n, myException): raise n except StopIteration: break except myException as e: # Deal with exception, log, print, continue, break etc else: # Consume n
这样,我仍然继承了Exception而没有引发它,这将导致生成器功能停止。主要缺点是我需要
isinstance在每次迭代时检查产生的结果。我不喜欢可以产生不同类型结果的生成器,但是将其用作最后的选择。



