Python exceptions

Here are some examples of common exceptions in Python along with explanations for each:

  • ZeroDivisionError:
  • Occurs when you attempt to divide by zero.

    try:
        result = 10 / 0
    except ZeroDivisionError as e:
        print(f"ZeroDivisionError: {e}")
  • ValueError:
  • Raised when a function receives an argument of the correct type but with an invalid value.

    try:
        num = int("not_an_integer")
    except ValueError as e:
        print(f"ValueError: {e}")
  • TypeError:
  • Occurs when an operation or function is applied to an object of an inappropriate type.

    try:
        result = "hello" + 42
    except TypeError as e:
        print(f"TypeError: {e}")
  • IndexError:
  • Raised when an index is out of range in a sequence (e.g., list, string, tuple).

    try:
        my_list = [1, 2, 3]
        value = my_list[5]
    except IndexError as e:
        print(f"IndexError: {e}")
  • KeyError:
  • Occurs when a dictionary key is not found.

    try:
        my_dict = {'name': 'Alice', 'age': 30}
        value = my_dict['gender']
    except KeyError as e:
        print(f"KeyError: {e}")
  • FileNotFoundError:
  • Raised when an attempt to open a file fails because the file does not exist.

    try:
        with open("nonexistent.txt", "r") as file:
            content = file.read()
    except FileNotFoundError as e:
        print(f"FileNotFoundError: {e}")
  • ImportError:
  • Occurs when an imported module or name cannot be found.

    try:
        import nonexistent_module
    except ImportError as e:
        print(f"ImportError: {e}")
  • AttributeError:
  • Raised when an object does not have the attribute you're trying to access.

    try:
        my_string = "Hello, world!"
        length = my_string.length
    except AttributeError as e:
        print(f"AttributeError: {e}")

These are just a few examples of common exceptions that you might encounter while working with Python code. It's important to understand these exceptions and how to handle them using "try" and "except" blocks to make your programs more robust and error-tolerant.