0
0
Pythonprogramming~10 mins

Exception hierarchy 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 all exceptions using the base exception class.

Python
try:
    x = 1 / 0
except [1]:
    print("Caught an exception")
Drag options to blanks, or click blank then click option'
AZeroDivisionError
BException
CArithmeticError
DBaseException
Attempts:
3 left
💡 Hint
Common Mistakes
Using Exception instead of BaseException catches most but not all exceptions.
Using specific exceptions like ZeroDivisionError won't catch all exceptions.
2fill in blank
medium

Complete the code to catch only errors related to arithmetic operations.

Python
try:
    y = 5 / 0
except [1]:
    print("Arithmetic error caught")
Drag options to blanks, or click blank then click option'
AArithmeticError
BBaseException
CZeroDivisionError
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Using ZeroDivisionError only catches division by zero, not other arithmetic errors.
Using BaseException is too broad.
3fill in blank
hard

Fix the error in the code to catch only division by zero exceptions.

Python
try:
    z = 10 / 0
except [1]:
    print("Division by zero caught")
Drag options to blanks, or click blank then click option'
AException
BArithmeticError
CZeroDivisionError
DBaseException
Attempts:
3 left
💡 Hint
Common Mistakes
Catching Exception or BaseException is too broad.
Using ArithmeticError catches more than just division by zero.
4fill in blank
hard

Fill both blanks to create a custom exception class inheriting from the correct base class.

Python
class MyError([1]):
    def __init__(self, message):
        super().__init__([2])
Drag options to blanks, or click blank then click option'
AException
BBaseException
CZeroDivisionError
Dmessage
Attempts:
3 left
💡 Hint
Common Mistakes
Inheriting from BaseException is not recommended for custom exceptions.
Passing the wrong argument to super().__init__ causes errors.
5fill in blank
hard

Fill all three blanks to catch multiple exceptions in one except block.

Python
try:
    a = int('abc')
    b = 1 / 0
except ([1], [2], [3]):
    print("Caught a value or arithmetic error")
Drag options to blanks, or click blank then click option'
AValueError
BZeroDivisionError
CArithmeticError
DTypeError
Attempts:
3 left
💡 Hint
Common Mistakes
Missing one of the exceptions causes some errors to go uncaught.
Using unrelated exceptions like TypeError will not catch these errors.