0
0
Pythonprogramming~10 mins

Exception chaining in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to raise a new exception while preserving the original one.

Python
try:
    x = 1 / 0
except ZeroDivisionError as e:
    raise ValueError('Invalid value') from [1]
Drag options to blanks, or click blank then click option'
ANone
BValueError
Ce
DZeroDivisionError
Attempts:
3 left
💡 Hint
Common Mistakes
Using the exception class name instead of the instance.
Using None which disables chaining.
Using a different exception variable.
2fill in blank
medium

Complete the code to suppress the original exception when raising a new one.

Python
try:
    int('abc')
except ValueError:
    raise RuntimeError('Conversion failed') from [1]
Drag options to blanks, or click blank then click option'
ANone
BValueError
CRuntimeError
De
Attempts:
3 left
💡 Hint
Common Mistakes
Using the original exception variable instead of None.
Not using the from keyword at all.
Using the exception class name.
3fill in blank
hard

Fix the error in the code to correctly chain exceptions.

Python
try:
    open('missing.txt')
except FileNotFoundError as err:
    raise Exception('File error') from [1]
Drag options to blanks, or click blank then click option'
Ae
Berr
CFileNotFoundError
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Using the exception class name instead of the variable.
Using a variable name not defined in the except block.
Omitting the from keyword.
4fill in blank
hard

Fill both blanks to create a dictionary of word lengths, filtering words longer than 3 characters.

Python
words = ['cat', 'house', 'dog', 'elephant']
lengths = {word: [1] for word in words if [2]
Drag options to blanks, or click blank then click option'
Alen(word)
Blen(word) > 3
Cword.startswith('e')
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself instead of its length.
Filtering by word starting letter instead of length.
Using incorrect comparison operators.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase keys and values greater than 0.

Python
data = {'a': 1, 'b': -2, 'c': 3}
result = { [1]: [2] for k, v in data.items() if v [3] 0 }
Drag options to blanks, or click blank then click option'
Ak.upper()
Bv
C>
Dk
Attempts:
3 left
💡 Hint
Common Mistakes
Using original keys without uppercase.
Filtering with wrong comparison operator.
Swapping keys and values.