Handle generator exceptions in its consumer

前端 未结 8 1610
迷失自我
迷失自我 2020-11-29 10:07

This is a follow-up to Handle an exception thrown in a generator and discusses a more general problem.

I have a function that reads data in different formats. All fo

8条回答
  •  一生所求
    2020-11-29 10:43

    About your point of propagating exception from generator to consuming function, you can try to use an error code (set of error codes) to indicate the error. Though not elegant that is one approach you can think of.

    For example in the below code yielding a value like -1 where you were expecting a set of positive integers would signal to the calling function that there was an error.

    In [1]: def f():
      ...:     yield 1
      ...:     try:
      ...:         2/0
      ...:     except ZeroDivisionError,e:
      ...:         yield -1
      ...:     yield 3
      ...:     
    
    
    In [2]: g = f()
    
    In [3]: next(g)
    Out[3]: 1
    
    In [4]: next(g)
    Out[4]: -1
    
    In [5]: next(g)
    Out[5]: 3
    

提交回复
热议问题