ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
def g():
    try:
        yield 1
        yield 2
    except KeyError:
        yield "caught"
    yield 3
it = g()
print(next(it), it.throw(KeyError), next(it))
  1. A. 1 2 3
  2. B. 1 caught 2
  3. C. 1 KeyError 3
  4. D. 1 caught 3

Correct answer: D. 1 caught 3

throw raises KeyError at the paused `yield 1`; the generator catches it and its next yield ('caught') becomes throw()'s return value. The next next() continues to yield 3.

More Python Programming questions

Exams that ask this topic