Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a specific exception like ZeroDivisionError instead of a generic one.
Using a non-exception class in except.
✗ Incorrect
Using 'Exception' catches all exceptions in Python, making it a generic handler.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name than the one declared after 'as'.
Not using 'as' to capture the exception.
✗ Incorrect
The variable after 'as' is used to refer to the caught exception; here it is 'e'.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to print a variable that was not assigned.
Not using 'as' to capture the exception instance.
✗ Incorrect
Without 'as' to capture the exception, you can only refer to the exception class, not an instance variable.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a specific exception instead of generic Exception.
Mismatch between variable name in except and print statement.
✗ Incorrect
Use 'Exception' to catch all errors and 'err' as the variable to hold the exception instance.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Not using the exception instance to get type and message.
✗ Incorrect
Use 'Exception' to catch all exceptions, 'err' as the variable name, and refer to 'err' to get the type and message.