0
0
Pythonprogramming~10 mins

Generic exception handling 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 any exception using a generic handler.

Python
try:
    x = 10 / 0
except [1]:
    print("An error occurred")
Drag options to blanks, or click blank then click option'
AException
BValueError
CZeroDivisionError
DTypeError
Attempts:
3 left
💡 Hint
Common Mistakes
Using a specific exception like ZeroDivisionError instead of a generic one.
Using a non-exception class in except.
2fill in blank
medium

Complete the code to print the exception message in a generic exception handler.

Python
try:
    int('abc')
except Exception as [1]:
    print(f"Error: {e}")
Drag options to blanks, or click blank then click option'
Aerror
Be
Cex
Derr
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name than the one declared after 'as'.
Not using 'as' to capture the exception.
3fill in blank
hard

Fix the error in the generic exception handling code below.

Python
try:
    result = 5 / 0
except Exception:
    print("Error:", [1])
Drag options to blanks, or click blank then click option'
Aerror
Be
Cexc
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to print a variable that was not assigned.
Not using 'as' to capture the exception instance.
4fill in blank
hard

Fill both blanks to catch any exception and print its message.

Python
try:
    open('missing_file.txt')
except [1] as [2]:
    print(f"Caught error: {err}")
Drag options to blanks, or click blank then click option'
AException
Berror
Cerr
DFileNotFoundError
Attempts:
3 left
💡 Hint
Common Mistakes
Using a specific exception instead of generic Exception.
Mismatch between variable name in except and print statement.
5fill in blank
hard

Fill all three blanks to catch any exception, print its type and message.

Python
try:
    int('xyz')
except [1] as [2]:
    print(f"Type: {type([3]).__name__}, Message: {err}")
Drag options to blanks, or click blank then click option'
AException
Berr
De
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Not using the exception instance to get type and message.