gen_yield_from_throw.py 578 B

123456789101112131415161718192021222324252627282930
  1. def gen():
  2. try:
  3. yield 1
  4. except ValueError:
  5. print("got ValueError from upstream!")
  6. yield "str1"
  7. raise TypeError
  8. def gen2():
  9. print((yield from gen()))
  10. g = gen2()
  11. print(next(g))
  12. print(g.throw(ValueError))
  13. try:
  14. print(next(g))
  15. except TypeError:
  16. print("got TypeError from downstream!")
  17. # case where generator doesn't intercept the thrown/injected exception
  18. def gen3():
  19. yield 123
  20. yield 456
  21. g3 = gen3()
  22. print(next(g3))
  23. try:
  24. g3.throw(StopIteration)
  25. except StopIteration:
  26. print('got StopIteration from downstream!')