0
0
Pythonprogramming~10 mins

Handling specific exceptions 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 catch a ZeroDivisionError exception.

Python
try:
    result = 10 / 0
except [1]:
    print("Cannot divide by zero!")
Drag options to blanks, or click blank then click option'
AZeroDivisionError
BTypeError
CValueError
DIndexError
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong exception type like ValueError or TypeError.
Not catching the exception at all.
2fill in blank
medium

Complete the code to catch a FileNotFoundError when opening a file.

Python
try:
    with open('missing.txt') as f:
        content = f.read()
except [1]:
    print("File not found.")
Drag options to blanks, or click blank then click option'
AIOError
BFileNotFoundError
COSError
DValueError
Attempts:
3 left
💡 Hint
Common Mistakes
Using IOError which is more general.
Catching the wrong exception like ValueError.
3fill in blank
hard

Fix the error in the except clause to catch the correct exception for invalid integer conversion.

Python
try:
    number = int('abc')
except [1]:
    print("Invalid integer!")
Drag options to blanks, or click blank then click option'
AValueError
BTypeError
CNameError
DZeroDivisionError
Attempts:
3 left
💡 Hint
Common Mistakes
Using TypeError which is for wrong data types, not invalid values.
Using ZeroDivisionError which is unrelated.
4fill in blank
hard

Fill both blanks to catch a KeyError and print a custom message.

Python
my_dict = {'a': 1}
try:
    value = my_dict[[1]]
except [2]:
    print("Key not found in dictionary.")
Drag options to blanks, or click blank then click option'
A'b'
B'a'
CKeyError
DIndexError
Attempts:
3 left
💡 Hint
Common Mistakes
Using a key that exists, so no exception is raised.
Catching the wrong exception like IndexError.
5fill in blank
hard

Fill all three blanks to catch a TypeError when adding incompatible types and print a message.

Python
try:
    result = [1] + [2]
except [3]:
    print("Cannot add these types!")
Drag options to blanks, or click blank then click option'
A5
B'hello'
CTypeError
D10
Attempts:
3 left
💡 Hint
Common Mistakes
Adding two numbers which does not raise an error.
Catching the wrong exception like ValueError.