ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
try:
    try:
        raise KeyError("k")
    except ValueError:
        print("vl")
except KeyError:
    print("kl")
  1. A. vl
  2. B. kl
  3. C. vl kl
  4. D. KeyError traceback

Correct answer: B. kl

The inner except only matches ValueError, so it does not catch the raised KeyError; the KeyError propagates out to the outer try, where the outer except KeyError catches it and prints 'kl'.

More Python Programming questions

Exams that ask this topic