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__)- A. ['t', 'e'] KeyError ValueError True
- B. ['t', 'e', 'f'] ValueError KeyError False
- C. ['t', 'e', 'f'] KeyError NoneType False
- 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
- What is printed? python it = iter(range(10)) print(5 in it, next(it), 2 in it, list(it), 9 in range(10))
- What is printed? python calls = [] def chk(x): calls.append(x) return x > 2 r1 = any(chk(x) for x in [1, 3, 5]) r2 = all([chk(x) for x in…
- What is printed? python a = [1, 2] b = [a] 3 a = 2 b[0].append(9) print(b[2], len(b))
- What is printed? python a = [1, 2] b = [a] 3 a = a 2 b[0].append(9) print(a, b[1])
- What is printed? python t = ([1],) try: t[0] += [2] except TypeError: pass try: t[0] = t[0] + [3] except TypeError: pass print(t)
- What is printed? python x = [1, 2, 3] y = x x[:] = [7] x = x + [8] print(y, x)