python-basic

⌘K
  1. Home
  2. Docs
  3. python-basic
  4. Error Type

Error Type

KeyError:

when a dictionary is accessed with a key that doesn’t exist.

my_dict = {"a": 1, "b": 2}
try:
    value = my_dict["c"]  # This will raise a KeyError
except KeyError as e:
    print("Caught a KeyError:", e)

ZeroDivisionError:

when an attempt is made to divide by zero.

try:
    result = 10 / 0  # This will raise a ZeroDivisionError
except ZeroDivisionError as e:
    print("Caught a ZeroDivisionError:", e)

FileNotFoundError:

when an attempt to open or manipulate a file that doesn’t exist.

try:
    with open("non_existent_file.txt", "r") as file:
        content = file.read()
except FileNotFoundError as e:
    print("Caught a FileNotFoundError:", e)

TypeError (for type casting):

when there is an issue with type casting.

try:
    num = int("abc")  # This will raise a TypeError
except TypeError as e:
    print("Caught a TypeError:", e)

AttributeError:

Raised when an attribute reference or assignment fails.

class Example:
    def __init__(self):
        self.value = 42

instance = Example()
try:
    print(instance.non_existent_attribute)  # This will raise an AttributeError
except AttributeError as e:
    print("Caught an AttributeError:", e)

How can we help?