ProgrammingVery hardProduct company OA

What is printed?

What is printed?
def f():
    log = []
    try:
        log.append("t")
        raise ValueError("v")
    except ValueError as e:
        log.append("e")
        raise KeyError("k") from e
    finally:
        log.append("f")
        print(log, end=" ")

try:
    f()
except Exception as ex:
    print(type(ex).__name__, type(ex.__cause__).__name__, ex.__suppress_context__)
  1. A. ['t', 'e'] KeyError ValueError True
  2. B. ['t', 'e', 'f'] ValueError KeyError False
  3. C. ['t', 'e', 'f'] KeyError NoneType False
  4. D. ['t', 'e', 'f'] KeyError ValueError True

Correct answer: D. ['t', 'e', 'f'] KeyError ValueError True

The ValueError is caught and a KeyError is raised from it. Before the KeyError leaves f, finally runs, appends 'f' and prints the full log. The caller receives the KeyError; raise ... from e sets __cause__ to the ValueError and sets __suppress_context__ to True so the traceback shows 'direct cause' wording.

More Python Programming questions

Exams that ask this topic