Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
Python - Custom Exceptions
What will be the output of this code?
try:
    raise KeyError('key missing')
except LookupError:
    print('Caught LookupError')
except KeyError:
    print('Caught KeyError')
ARuntimeError
BCaught KeyError
CNo output
DCaught LookupError
Step-by-Step Solution
Solution:
  1. Step 1: Identify exception raised

    The code raises a KeyError, which is a subclass of LookupError.
  2. Step 2: Match except blocks order

    Python checks except blocks in order. The first except block matches LookupError, which is a parent of KeyError, so it catches the exception and prints 'Caught LookupError'. The second except block is not reached.
  3. Final Answer:

    Caught LookupError -> Option D
  4. Quick Check:

    Parent except block catches subclass exceptions first [OK]
Quick Trick: Parent exception blocks catch subclass exceptions if placed first [OK]
Common Mistakes:
  • Expecting KeyError block to run before LookupError
  • Ignoring except block order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes