CS FundamentalsVery hardProduct-company placement · Python interview

What does this code print (lines joined by ' / ')?

What does this code print (lines joined by ' / ')?
class Guard:
    def __enter__(self):
        print("enter")
        return self
    def __exit__(self, exc_type, exc, tb):
        print("exit", exc_type.__name__ if exc_type else None)
        return exc_type is ValueError
for err in (ValueError, KeyError):
    try:
        with Guard():
            raise err("x")
        print("after")
    except Exception as e:
        print("caught", type(e).__name__)
  1. A. enter / exit ValueError / caught ValueError / enter / exit KeyError / caught KeyError
  2. B. enter / exit ValueError / after / enter / exit KeyError / after
  3. C. enter / exit ValueError / after / enter / exit KeyError / caught KeyError
  4. D. enter / caught ValueError / enter / caught KeyError

Correct answer: C. enter / exit ValueError / after / enter / exit KeyError / caught KeyError

__exit__ always runs; returning True suppresses the exception. For ValueError it returns True, so execution continues at 'after'. For KeyError it returns False, so the exception propagates to the except block.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic