Bird
0
0

Which code correctly implements exception chaining?

hard📝 Application Q15 of 15
Python - Advanced Exception Handling

You want to write a function that reads a number from a string and raises a custom MyError if conversion fails, but also keep the original error for debugging. Which code correctly implements exception chaining?

class MyError(Exception):
    pass

def read_number(s):
    try:
        return int(s)
    except ValueError as e:
        ???
Araise MyError('Invalid number') from e
Braise MyError('Invalid number')
Craise ValueError('Invalid number') from e
Draise MyError('Invalid number', e)
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    The function should raise MyError but keep original ValueError linked for debugging.
  2. Step 2: Use exception chaining syntax

    Using raise MyError(...) from e correctly chains the new error to the original.
  3. Step 3: Evaluate options

    raise MyError('Invalid number') from e uses correct chaining syntax; others either lose original error or misuse arguments.
  4. Final Answer:

    raise MyError('Invalid number') from e -> Option A
  5. Quick Check:

    Use 'raise ... from e' to chain custom errors [OK]
Quick Trick: Chain custom errors with 'raise ... from e' [OK]
Common Mistakes:
  • Not chaining original error
  • Passing original error as argument incorrectly
  • Raising wrong exception type

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes