Bird
Raised Fist0

What will be the output of this code?

medium📝 Predict Output Q13 of Q15
Python - Advanced Exception Handling

What will be the output of this code?

def f():
    try:
        1 / 0
    except ZeroDivisionError as e:
        raise ValueError("Invalid value") from e

try:
    f()
except Exception as ex:
    print(type(ex).__name__)
    print(ex.__cause__)
AZeroDivisionError\nNone
BValueError\nNone
CValueError\ndivision by zero
DZeroDivisionError\nValueError('Invalid value')
Step-by-Step Solution
Solution:
  1. Step 1: Trace function f()

    Inside f(), dividing by zero raises ZeroDivisionError, caught as e.
  2. Step 2: Raise ValueError chained from ZeroDivisionError

    The code raises ValueError with message "Invalid value" from e, linking the original ZeroDivisionError.
  3. Step 3: Catch exception and print details

    The outer try-except catches the ValueError, prints its type, then prints its __cause__, which is the original ZeroDivisionError.
  4. Final Answer:

    ValueError division by zero -> Option C
  5. Quick Check:

    Chained error shows new error and original cause [OK]
Quick Trick: Chained exceptions show new error and original cause [OK]
Common Mistakes:
MISTAKES
  • Expecting __cause__ to be None
  • Confusing error types printed
  • Missing that ValueError is raised

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes