0
0
Pythonprogramming~10 mins

Try–except execution flow 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 division by zero error.

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 a wrong exception type like ValueError or TypeError.
Not catching the exception at all.
2fill in blank
medium

Complete the code to print a message when no error occurs.

Python
try:
    print("Hello")
except Exception:
    print("Error occurred")
else:
    [1]
Drag options to blanks, or click blank then click option'
Apass
Bprint("No errors!")
Craise
Dbreak
Attempts:
3 left
💡 Hint
Common Mistakes
Using raise inside else which re-raises an error.
Using break outside loops causing syntax error.
3fill in blank
hard

Fix the error in the except block to catch any exception.

Python
try:
    x = int('abc')
except [1]:
    print("Caught an error")
Drag options to blanks, or click blank then click option'
AException
BError
CBaseException
DValueError
Attempts:
3 left
💡 Hint
Common Mistakes
Using Error which is not a built-in exception class.
Using BaseException which is too broad and not recommended.
4fill in blank
hard

Fill both blanks to handle a file error and print a message.

Python
try:
    with open('file.txt', '[1]') as f:
        content = f.read()
except [2]:
    print("File not found")
Drag options to blanks, or click blank then click option'
Ar
Bw
CFileNotFoundError
DIOError
Attempts:
3 left
💡 Hint
Common Mistakes
Using write mode 'w' which creates the file instead of reading.
Catching IOError which is more general than FileNotFoundError.
5fill in blank
hard

Fill all three blanks to handle multiple exceptions and print the error type.

Python
try:
    num = int(input('Enter a number: '))
    result = 10 / num
except [1]:
    print("Cannot convert input to integer")
except [2]:
    print("Division by zero error")
except [3]:
    print("Some other error occurred")
Drag options to blanks, or click blank then click option'
AValueError
BZeroDivisionError
CException
DTypeError
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up exception types and their purposes.
Not including a general exception handler.