ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
def h():
    try:
        x = 1 / 0
    except ZeroDivisionError:
        return "caught"
    else:
        return "no error"
    finally:
        print("always")
print(h())
  1. A. caught always
  2. B. always caught
  3. C. no error always
  4. D. always no error

Correct answer: B. always caught

finally runs just before the function's already-decided return value is actually handed back, so 'always' prints first, and then h() returns 'caught' (from the except clause, since the else clause never runs after an exception).

More Python Programming questions

Exams that ask this topic