Challenge - 5 Problems
Exception Chaining Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of chained exceptions with raise from
What is the output of this Python code when executed?
Python
def func(): try: x = 1 / 0 except ZeroDivisionError as e: raise ValueError("Invalid value") from e try: func() except Exception as ex: print(type(ex).__name__) print(ex) print(type(ex.__cause__).__name__) print(ex.__cause__)
Attempts:
2 left
💡 Hint
Remember that 'raise ... from ...' sets the __cause__ attribute of the new exception.
✗ Incorrect
The ValueError is raised from the original ZeroDivisionError. The __cause__ attribute links them, so ex is ValueError and ex.__cause__ is ZeroDivisionError.
❓ Predict Output
intermediate2:00remaining
Effect of exception chaining without 'from'
What will be printed by this code?
Python
try: try: int('abc') except ValueError: raise RuntimeError('Conversion failed') except Exception as e: print(type(e).__name__) print(e) print(e.__cause__)
Attempts:
2 left
💡 Hint
Without 'from', the __cause__ attribute is not set automatically.
✗ Incorrect
Raising a new exception without 'from' does not link the original exception as the cause, so __cause__ is None.
🔧 Debug
advanced2:00remaining
Identify the error in exception chaining syntax
Which option contains a syntax error related to exception chaining?
Attempts:
2 left
💡 Hint
Check the keyword used to chain exceptions.
✗ Incorrect
The keyword 'with' is invalid for exception chaining; the correct keyword is 'from'.
❓ Predict Output
advanced2:00remaining
Output of nested exception chaining with __context__
What will this code print?
Python
def f(): try: int('a') except ValueError: try: 1/0 except ZeroDivisionError: raise RuntimeError('Runtime problem') try: f() except Exception as e: print(type(e).__name__) print(e) print(type(e.__context__).__name__) print(e.__context__)
Attempts:
2 left
💡 Hint
When an exception is raised during handling another, __context__ stores the original exception.
✗ Incorrect
The RuntimeError is raised inside the except block for ZeroDivisionError, so __context__ is ZeroDivisionError.
🧠 Conceptual
expert2:00remaining
Understanding implicit vs explicit exception chaining
Which statement best describes the difference between implicit and explicit exception chaining in Python?
Attempts:
2 left
💡 Hint
Think about how Python links exceptions automatically versus when you use 'from'.
✗ Incorrect
Explicit chaining uses 'raise ... from ...' to set __cause__. Implicit chaining happens automatically and sets __context__ when an exception occurs during handling another.