Bird
0
0

Given this code, what will be printed?

hard📝 Application Q9 of 15
Python - Exception Handling Fundamentals
Given this code, what will be printed?
try:
    d = {'a': 1}
    print(d['b'])
except KeyError:
    print('KeyError caught')
except Exception:
    print('General exception caught')
AGeneral exception caught
BBoth messages printed
CNo output, program crashes
DKeyError caught
Step-by-Step Solution
Solution:
  1. Step 1: Identify the exception raised

    Accessing d['b'] raises KeyError because 'b' is not a key in the dictionary.
  2. Step 2: Determine which except block runs

    KeyError except block matches and runs, printing 'KeyError caught'.
  3. Final Answer:

    KeyError caught -> Option D
  4. Quick Check:

    Specific KeyError except runs first [OK]
Quick Trick: Specific exception blocks catch matching errors first [OK]
Common Mistakes:
  • Expecting general exception block to run
  • Thinking program crashes
  • Assuming both except blocks run

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes