Bird
Raised Fist0
Pythonprogramming~10 mins

Common exception types in Python - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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'
AValueError
BZeroDivisionError
CTypeError
DIndexError
Attempts:
3 left
💡 Hint
Common Mistakes
Using ValueError instead of ZeroDivisionError.
Using TypeError which is for wrong data types.
2fill in blank
medium

Complete the code to catch an error when accessing a list index that does not exist.

Python
my_list = [1, 2, 3]
try:
    print(my_list[5])
except [1]:
    print("Index out of range!")
Drag options to blanks, or click blank then click option'
AKeyError
BValueError
CAttributeError
DIndexError
Attempts:
3 left
💡 Hint
Common Mistakes
Using KeyError which is for dictionary keys.
Using AttributeError which is for missing object attributes.
3fill in blank
hard

Fix the error in the code by catching the correct exception type when converting a string to an integer.

Python
user_input = "abc"
try:
    number = int(user_input)
except [1]:
    print("Invalid number!")
Drag options to blanks, or click blank then click option'
AValueError
BTypeError
CNameError
DZeroDivisionError
Attempts:
3 left
💡 Hint
Common Mistakes
Using TypeError which is for wrong data types, not invalid values.
Using ZeroDivisionError which is unrelated.
4fill in blank
hard

Fill both blanks to catch errors when opening a file that does not exist and when reading from it.

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

Fill all three blanks to create a dictionary comprehension that includes only keys with string values longer than 3 characters.

Python
data = {'a': 'cat', 'b': 'elephant', 'c': 42}
result = {k: v for k, v in data.items() if isinstance(v, [1]) and len(v) [2] [3]
Drag options to blanks, or click blank then click option'
Astr
B>
C3
Dint
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'int' instead of 'str' for type check.
Using '<' instead of '>' for length comparison.

Practice

(1/5)
1. Which exception is raised when you try to divide a number by zero in Python?
easy
A. ValueError
B. ZeroDivisionError
C. IndexError
D. TypeError

Solution

  1. Step 1: Understand division by zero

    Dividing any number by zero is mathematically undefined and causes an error in Python.
  2. Step 2: Identify the exception type

    Python raises a ZeroDivisionError when division by zero occurs.
  3. Final Answer:

    ZeroDivisionError -> Option B
  4. Quick Check:

    Division by zero = ZeroDivisionError [OK]
Hint: Division by zero always raises ZeroDivisionError [OK]
Common Mistakes:
  • Confusing ZeroDivisionError with ValueError
  • Thinking IndexError occurs for division
  • Assuming TypeError is raised for zero division
2. Which of the following code snippets will raise a ValueError?
easy
A. open('file.txt')
B. 5 / 0
C. my_list[10] where my_list has 5 elements
D. int('abc')

Solution

  1. Step 1: Analyze each option for ValueError

    int('abc') tries to convert a non-numeric string to int, which causes ValueError.
  2. Step 2: Check other options for different exceptions

    5 / 0 causes ZeroDivisionError, C causes IndexError, A may cause FileNotFoundError.
  3. Final Answer:

    int('abc') -> Option D
  4. Quick Check:

    Invalid int conversion = ValueError [OK]
Hint: ValueError occurs when conversion or value is invalid [OK]
Common Mistakes:
  • Confusing ZeroDivisionError with ValueError
  • Assuming file open errors cause ValueError
  • Mixing IndexError with ValueError
3. What will be the output of this code?
my_list = [1, 2, 3]
print(my_list[3])
medium
A. IndexError
B. 3
C. None
D. ValueError

Solution

  1. Step 1: Understand list indexing

    List indices start at 0, so valid indices for my_list are 0, 1, 2.
  2. Step 2: Accessing index 3

    Index 3 is out of range, so Python raises an IndexError.
  3. Final Answer:

    IndexError -> Option A
  4. Quick Check:

    Out of range index = IndexError [OK]
Hint: Accessing invalid list index raises IndexError [OK]
Common Mistakes:
  • Thinking it returns last element
  • Assuming None is returned for invalid index
  • Confusing IndexError with ValueError
4. Identify the error in this code snippet:
try:
    x = int('hello')
except ZeroDivisionError:
    print('Cannot divide by zero')
medium
A. Wrong exception caught, should catch ValueError
B. SyntaxError due to missing colon
C. No error, code runs fine
D. ZeroDivisionError will be raised

Solution

  1. Step 1: Analyze the try block

    int('hello') raises ValueError because 'hello' cannot convert to int.
  2. Step 2: Check except block

    Except block catches ZeroDivisionError, which does not handle ValueError, so error is uncaught.
  3. Final Answer:

    Wrong exception caught, should catch ValueError -> Option A
  4. Quick Check:

    Exception type mismatch = catch correct exception [OK]
Hint: Catch the exact exception your code may raise [OK]
Common Mistakes:
  • Catching wrong exception type
  • Assuming code runs without error
  • Confusing syntax errors with exception handling
5. You want to safely convert user input to an integer and print it. Which code correctly handles invalid input without crashing?
hard
A. try: num = int(input()) except ZeroDivisionError: print('Invalid number')
B. num = int(input()) print(num)
C. try: num = int(input()) except ValueError: print('Invalid number')
D. num = input() print(int(num))

Solution

  1. Step 1: Understand input conversion risks

    User input may not be a valid integer, causing ValueError on conversion.
  2. Step 2: Check exception handling

    try: num = int(input()) except ValueError: print('Invalid number') uses try-except to catch ValueError and print a message, preventing crash.
  3. Final Answer:

    try-except catching ValueError with message -> Option C
  4. Quick Check:

    Handle invalid input with ValueError catch [OK]
Hint: Use try-except to catch ValueError on int conversion [OK]
Common Mistakes:
  • Not catching exceptions causing program crash
  • Catching wrong exception type like ZeroDivisionError
  • Assuming input is always valid integer