0
0
Pythonprogramming~10 mins

Try–except–finally behavior 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.

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

Complete the code to always print 'Done' after the try-except block.

Python
try:
    x = int('abc')
except ValueError:
    print('Invalid number')
finally:
    [1]('Done')
Drag options to blanks, or click blank then click option'
Ainput
Breturn
Cprint
Draise
Attempts:
3 left
💡 Hint
Common Mistakes
Using input instead of print.
Trying to raise an exception inside finally without reason.
3fill in blank
hard

Fix the error in the except clause to catch the correct exception.

Python
try:
    numbers = [1, 2, 3]
    print(numbers[5])
except [1]:
    print('Index out of range')
Drag options to blanks, or click blank then click option'
AKeyError
BTypeError
CValueError
DIndexError
Attempts:
3 left
💡 Hint
Common Mistakes
Using KeyError which is for dictionaries.
Using ValueError which is for wrong values.
4fill in blank
hard

Fill both blanks to catch a ValueError and print a message, then always print 'Finished'.

Python
try:
    num = int('abc')
except [1]:
    print('Conversion failed')
finally:
    [2]('Finished')
Drag options to blanks, or click blank then click option'
AValueError
Bprint
CZeroDivisionError
Dinput
Attempts:
3 left
💡 Hint
Common Mistakes
Catching the wrong exception type.
Using input instead of print in finally.
5fill in blank
hard

Fill all three blanks to catch a KeyError, print the error message, and always print 'End'.

Python
my_dict = {'a': 1}
try:
    value = my_dict[[1]]
except [2] as e:
    [3](f'Error: {e}')
finally:
    print('End')
Drag options to blanks, or click blank then click option'
A'b'
BKeyError
Cprint
D'a'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a key that exists, so no error occurs.
Catching the wrong exception type.
Not printing the error message correctly.