7.2 Exception Types

7.2 Exception Types

Overview of Python's most common built-in exceptions, such as ValueError, TypeError, IndexError, KeyError, and FileNotFoundError.

Python has a rich hierarchy of built-in exception types. It is good practice to catch specific types of exceptions rather than a generic `Exception`, as this allows you to handle different errors in different ways and prevents hiding unexpected errors you had not anticipated.

Common Exception Types

  • SyntaxError: The only error you cannot "catch" with `try-except`. It is caused by a syntax error in the code structure, detected before execution.
  • NameError: Occurs when you try to use a variable or function that has not been defined.
  • TypeError: Occurs when an operation or function is applied to an object of an inappropriate type (e.g., `len(5)` or `"hello" + 2`).
  • ValueError: Occurs when a function receives an argument of the correct type but an inappropriate value (e.g., `int("abc")`).
  • IndexError: Occurs when you try to access an index outside the bounds of a sequence (list, tuple).
  • KeyError: Occurs when you try to access a key that does not exist in a dictionary.
  • FileNotFoundError: Occurs when you try to open a file that does not exist.
# Catching multiple exceptions
my_list = [1, 2, 3]
my_dict = {'a': 1}

try:
    # Change the choice to see different errors
    error_choice = 'list' # or 'dict'

    if error_choice == 'list':
        print(my_list[5]) # raises IndexError
    elif error_choice == 'dict':
        print(my_dict['b']) # raises KeyError

except (IndexError, KeyError) as e:
    print(f"Caught a collection access error: {type(e).__name__}")

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.