Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong exception type like ValueError or TypeError.
Not catching the exception at all.
✗ Incorrect
The ZeroDivisionError is raised when division by zero occurs. Catching it allows handling this specific error.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using IOError which is more general.
Catching the wrong exception like ValueError.
✗ Incorrect
FileNotFoundError is raised when trying to open a file that does not exist.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using TypeError which is for wrong data types, not invalid values.
Using ZeroDivisionError which is unrelated.
✗ Incorrect
Converting a non-numeric string to int raises a ValueError.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a key that exists, so no exception is raised.
Catching the wrong exception like IndexError.
✗ Incorrect
Accessing a missing key 'b' raises KeyError, which we catch to print a message.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Adding two numbers which does not raise an error.
Catching the wrong exception like ValueError.
✗ Incorrect
Adding an integer (5) and a string ('hello') raises a TypeError, which we catch.