Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Exception chaining
📖 Scenario: Imagine you are writing a program that reads numbers from a list and divides 100 by each number. Sometimes, the numbers might cause errors like division by zero or invalid data types.
🎯 Goal: You will create a program that uses try and except blocks to catch errors and use exception chaining to show the original error when a new error is raised.
📋 What You'll Learn
Create a list called numbers with the values 10, 0, 'a', and 5
Create a variable called results and set it to an empty list
Use a for loop with variable num to iterate over numbers
Inside the loop, use a try block to divide 100 by num
If an exception occurs, catch it as e and raise a new ValueError with the message 'Invalid number: {num}' using exception chaining
Append the division result to results if no exception occurs
Print the results list at the end
💡 Why This Matters
🌍 Real World
Exception chaining helps programmers understand the root cause of errors while providing clearer messages. This is useful in debugging real applications where multiple errors can happen.
💼 Career
Knowing how to use exception chaining is important for writing robust Python code that is easier to maintain and debug in professional software development.
Progress0 / 4 steps
1
Create the list of numbers
Create a list called numbers with these exact values: 10, 0, 'a', and 5
Python
Hint
Use square brackets to create a list with the exact values in order.
2
Create an empty list to store results
Create a variable called results and set it to an empty list []
Python
Hint
Use empty square brackets to create an empty list.
3
Use a for loop with try-except and exception chaining
Use a for loop with variable num to iterate over numbers. Inside the loop, use a try block to divide 100 by num and append the result to results. If an exception occurs, catch it as e and raise a new ValueError with the message f'Invalid number: {num}' using exception chaining with from e.
Python
Hint
Remember to use 'from e' after raising the new ValueError to chain exceptions.
4
Print the results list
Write print(results) to display the list of successful division results after the loop.
Python
Hint
The print should show the list with the results of dividing 100 by 10 and 5 only.
Practice
(1/5)
1.
What does raise NewError() from OriginalError() do in Python?
easy
A. It links the new error to the original error, showing both in the traceback.
B. It ignores the original error and raises only the new error.
C. It catches the original error and prevents any error from being raised.
D. It raises both errors separately without linking them.
Solution
Step 1: Understand exception chaining syntax
The syntax raise NewError() from OriginalError() explicitly links the new error to the original one.
Step 2: Effect on traceback
This chaining shows both errors in the error message, helping to trace the root cause.
Final Answer:
It links the new error to the original error, showing both in the traceback. -> Option A
Quick Check:
Exception chaining = linked errors [OK]
Hint: Remember 'from' links errors to show full traceback [OK]
Common Mistakes:
Thinking it hides the original error
Believing it raises errors separately
Confusing it with catching exceptions
2.
Which of the following is the correct syntax to chain exceptions in Python?
try:
1 / 0
except ZeroDivisionError as e:
???
easy
A. raise ValueError() and e
B. raise ValueError() from e
C. raise ValueError() with e
D. raise ValueError(e)
Solution
Step 1: Recall correct chaining syntax
To chain exceptions, use raise NewError() from original_error.
Step 2: Match syntax to options
raise ValueError() from e uses raise ValueError() from e, which is correct syntax.
Final Answer:
raise ValueError() from e -> Option B
Quick Check:
Correct chaining syntax uses 'from' keyword [OK]
Hint: Use 'raise ... from ...' to chain exceptions [OK]
Common Mistakes:
Using parentheses incorrectly
Using 'with' or 'and' instead of 'from'
Passing original error as argument without 'from'
3.
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__)
medium
A. ZeroDivisionError\nNone
B. ValueError\nNone
C. ValueError\ndivision by zero
D. ZeroDivisionError\nValueError('Invalid value')
Solution
Step 1: Trace function f()
Inside f(), dividing by zero raises ZeroDivisionError, caught as e.
Step 2: Raise ValueError chained from ZeroDivisionError
The code raises ValueError with message "Invalid value" from e, linking the original ZeroDivisionError.
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.
Final Answer:
ValueError
division by zero -> Option C
Quick Check:
Chained error shows new error and original cause [OK]
Hint: Chained exceptions show new error and original cause [OK]
Common Mistakes:
Expecting __cause__ to be None
Confusing error types printed
Missing that ValueError is raised
4.
Identify the error in this code snippet:
try:
int('abc')
except ValueError as e:
raise TypeError('Wrong type') from
medium
A. ValueError because int conversion failed
B. TypeError because 'from' cannot be used here
C. No error, code runs fine
D. SyntaxError due to incomplete 'from' statement
Solution
Step 1: Check the 'raise' statement syntax
The statement ends with 'from' but does not specify the original exception after it.
Step 2: Understand Python syntax rules
The 'from' keyword must be followed by an exception instance or variable; missing this causes SyntaxError.
Final Answer:
SyntaxError due to incomplete 'from' statement -> Option D
Quick Check:
Incomplete 'from' causes SyntaxError [OK]
Hint: Always provide an exception after 'from' [OK]
Common Mistakes:
Leaving 'from' without exception
Thinking 'from' is optional
Confusing runtime error with syntax error
5.
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:
???
hard
A. raise MyError('Invalid number') from e
B. raise MyError('Invalid number')
C. raise ValueError('Invalid number') from e
D. raise MyError('Invalid number', e)
Solution
Step 1: Understand the goal
The function should raise MyError but keep original ValueError linked for debugging.
Step 2: Use exception chaining syntax
Using raise MyError(...) from e correctly chains the new error to the original.
Step 3: Evaluate options
raise MyError('Invalid number') from e uses correct chaining syntax; others either lose original error or misuse arguments.
Final Answer:
raise MyError('Invalid number') from e -> Option A
Quick Check:
Use 'raise ... from e' to chain custom errors [OK]
Hint: Chain custom errors with 'raise ... from e' [OK]