Bird
Raised Fist0

Given this code, what will be printed?

hard🚀 Application Q8 of Q15
Python - Advanced Exception Handling

Given this code, what will be printed?

def func():
    try:
        {}['key']
    except KeyError as e:
        try:
            1 / 0
        except ZeroDivisionError as ze:
            raise RuntimeError('Runtime problem') from ze

try:
    func()
except Exception as ex:
    print(ex)
    print(ex.__cause__)
A'key' Runtime problem
BRuntime problem division by zero
CKeyError None
DRuntime problem None
Step-by-Step Solution
Solution:
  1. Step 1: Trace func() execution

    Accessing key in empty dict raises KeyError, caught but ignored; then 1/0 raises ZeroDivisionError chained to RuntimeError.
  2. Step 2: Outer except prints RuntimeError and its cause

    Prints 'Runtime problem' and original 'division by zero' cause.
  3. Final Answer:

    Runtime problem division by zero -> Option B
  4. Quick Check:

    Nested chaining shows RuntimeError and ZeroDivisionError cause [OK]
Quick Trick: Nested exceptions chain causes through layers [OK]
Common Mistakes:
MISTAKES
  • Expecting KeyError to be printed
  • Ignoring nested exception chaining
  • Assuming cause is None

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes